gpt4 book ai didi

c - 如果我使用 "invalid free or delete",为什么 Valgrind 会生成 "realloc()"?

转载 作者:行者123 更新时间:2023-12-04 11:43:15 25 4
gpt4 key购买 nike

在使用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;
}

最佳答案

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

引用:

C99 标准 7.20.3.4-1:realloc 函数:

概要

#include
void *realloc(void *ptr, size_t size);

第 3 段:

If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, ifptr does not match a pointer earlier returned by the calloc,malloc,or realloc function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined. If memory for the newobject cannot be allocated, the old object is not deallocated and its value is unchanged.

请注意,在您的情况下,传递给 realloc 的指针不是 null ans 也未通过调用 callocmallocrealloc 打破了标准规定的要求,因此出现了未定义的行为。

关于c - 如果我使用 "invalid free or delete",为什么 Valgrind 会生成 "realloc()"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8623233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com