c语言 - 如果我使用"realloc()",为什么瓦尔格林德会产生"invalid free or delete"?



在使用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("%sn%sn",name[0],name[1]);
  realloc(name,3);
  name[2]="vishwa";
  printf("%sn",name[2]);
 return 0;
}

你的程序导致未定义行为,而valgrind正确地指出了它。

参考:

C99标准7.20.3.4-1:realloc函数

简介

# include
Void *realloc(Void *ptr, size_t);

帕拉3:

如果ptr为空指针,则realloc函数的行为与指定大小的malloc函数相同。否则,如果ptr不匹配之前由calloc, mallocrealloc函数返回的指针,或者如果空间已经被调用freerealloc函数释放,则行为是未定义的。如果不能为新对象分配内存,则不释放旧对象,其值保持不变。

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

只能对malloc或realloc返回的指针使用realloc。也就是说,你的程序是错误的。

最新更新