C free()如何工作? [英] How does C free() work?
问题描述
可能重复:
malloc()和free()如何工作
Possible Duplicate:
How malloc() and free() work
#include <stdio.h>
#include <stdlib.h>
int * alloc()
{
int *p = (int *)calloc(5,4);
printf("%d\n",p);
return p;
}
int main()
{
int *p = alloc();
free(p);
printf("%d\n",p);
p[0] = 1;
p[1] = 2;
printf("%d %d\n",p[0],p[1]);
}
对于代码段,我首先分配5个整数.然后我释放内存. 当我打印f p时,为什么p sill具有与首先分配的内存地址相同的值? 而且我还可以为p [0]和p [1]赋值.这是否意味着free()什么也不做?有一次,我 分配内存,虽然我已经释放了它,但以后可以使用.
As to the code segment, I allocate 5 ints,first. And then I free the memory. When I printf p, why does p sill have a value same to the memory address allocated first? And I also can assign value to p[0] and p[1]. Does this mean free() do nothing? Once I allocate memory, I can use later though I have freed it.
推荐答案
free
释放该地址的内存 .它不会更改p
变量本身.但是,在那之后用p
进行任何操作都是未定义的行为.如果您在释放后立即使用它,它似乎可以工作,但是它仍然是完全错误的,并且可能导致崩溃甚至更糟.
free
releases the memory at that address. It doesn't change the p
variable itself. However, doing anything with p
after that point is undefined behavior. It may seem to work if you use it immediately after freeing, but it's still completely wrong, and could cause a crash or worse.
free
是特定于实现的.但是,在大多数实现中,它将写入堆中的簿记数据,以注意该内存现在可用.例如,它可能将特定的块标记为未使用,或将其与相邻的空闲块组合.
free
is implementation-specific. However, on most implementations, it will write to book-keeping data in the heap to note that the memory is now available. For instance, it might mark a particular chunk as unused, or combine the chunk with an adjacent free one.
请注意,对于指针使用%d
也是未定义的.
Note that using %d
for a pointer is also undefined.
这篇关于C free()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!