如果您尝试释放未使用malloc/calloc
分配的内存,会发生什么情况
我的意思是:
void main()
{
int temp = 0;
int *ptr = &temp;
free(ptr);
}
我以为free()
会返回一些错误代码,但是free()
没有返回值。
发布于 2011-11-21 16:07:16
如果你在之前没有分配的指针上调用free()
,它将触发未定义的行为。
函数释放ptr指向的内存空间,这些内存空间必须是由先前调用malloc()、calloc()或realloc()返回的。否则,或者如果之前已经调用了free(ptr),则会发生未定义的行为。如果ptr为NULL,则不执行任何操作。
发布于 2011-11-21 16:22:07
添加到Malcolm's answer:这是ISO/IEC9899:1999,7.20.3.2未定义的行为:
否则,如果参数与
、malloc或realloc函数先前返回的指针不匹配...行为是未定义的。
请参阅此处的标准草案:http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf。
发布于 2011-11-21 16:21:45
我对上面的代码做了一点扩展:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int temp = 0;
int *ptr = &temp;
printf("Before: %0X\n", ptr);
free(ptr);
printf("After: %0X\n", ptr);
getchar();
}
如果此代码是由Visual Studio2010编译的,则在调试配置中,调用free
会启动“调试断言失败”消息。此错误消息来自dbgheap.c:
/*
* If this ASSERT fails, a bad pointer has been passed in. It may be
* totally bogus, or it may have been allocated from another heap.
* The pointer MUST come from the 'local' heap.
*/
_ASSERTE(_CrtIsValidHeapPointer(pUserData));
使用MinGW-GCC编译,生成的exe运行时没有错误( "After:...“行显示与“之前:...”相同的ptr值。行)。
https://stackoverflow.com/questions/8214692
复制相似问题