【问题标题】:Why Valgrind producing "invalid free or delete" if I use "realloc()"?如果我使用“realloc()”,为什么 Valgrind 会产生“无效的免费或删除”?
【发布时间】:2023-04-06 00:43:01
【问题描述】:

在使用 realloc() 时,我使用 valgrind 进行了如下检查

 valgrind --tool=memcheck --leak-check=yes --show-reachable=yes a.out

valgrind产生的错误信息是

==6402== Memcheck, a memory error detector.
==6402== Copyright (C) 2002-2005, and GNU GPL'd, by Julian Seward et al.
==6402== Using LibVEX rev 1575, a library for dynamic binary translation.
==6402== Copyright (C) 2004-2005, and GNU GPL'd, by OpenWorks LLP.
==6402== Using valgrind-3.1.1, a dynamic binary instrumentation framework.
==6402== Copyright (C) 2000-2005, and GNU GPL'd, by Julian Seward et al.
==6402== For more details, rerun with: -v
==6402==
dinesh
vignesh
==6402== Invalid free() / delete / delete[]
==6402==    at 0x4905E12: realloc (vg_replace_malloc.c:306)
==6402==    by 0x400539: main (in /user/gur29597/mysourcecode/VMake/a.out)
==6402==  Address 0x7FF000830 is on thread 1's stack
vishwa
==6402==
==6402== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 1)
==6402== malloc/free: in use at exit: 0 bytes in 0 blocks.
==6402== malloc/free: 1 allocs, 1 frees, 3 bytes allocated.
==6402== For counts of detected errors, rerun with: -v
==6402== All heap blocks were freed -- no leaks are possible.

我的代码如下,

#include<stdio.h>

int main()
{
  char *name[2];

 name[0]="dinesh";

 name[1]="vignesh";

  printf("%s\n%s\n",name[0],name[1]);

  realloc(name,3);

  name[2]="vishwa";

  printf("%s\n",name[2]);

 return 0;
}

【问题讨论】:

  • 除了下面的正确答案之外,您还应该小心将字节大小传递给realloc()。即使name 正确指向分配有malloc() 的块,realloc(name,3); 也不会做你想做的事。

标签: c valgrind realloc


【解决方案1】:

您的程序导致 未定义的行为 并且 valgrind 正确指出了它。

参考:

C99 标准 7.20.3.4-1:realloc 函数:

简介

#包括
void *realloc(void *ptr, size_t size);

第 3 段:

如果ptr 是空指针,则realloc 函数的行为与指定大小的malloc 函数类似。否则,ifptr 与先前由 calloc、malloc 或 realloc 函数返回的指针不匹配,或者如果空间已通过调用 free 或 realloc 函数被释放,则行为是未定义。如果新对象的内存无法分配,旧对象不会被释放,其值不变。

请注意,在您的情况下,传递给realloc 的指针不是空的,也没有通过调用calloc、malloc 或realloc 接收到,这违反了标准规定的要求,因此是未定义的行为。

【讨论】:

    【解决方案2】:

    您只能对从 malloc 或 realloc 返回的指针使用 realloc。换句话说,你的程序是错误的。

    【讨论】:

    • +1。此外,该特定错误的原因是 realloc 有时被实现为简单的 free() + malloc()。
    猜你喜欢
    • 2012-05-15
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    相关资源
    最近更新 更多