被 malloc() 分配后释放的内存会发生什么?

What happens to the memory which is freed after being allocated by malloc()?

释放后使用 malloc() 分配的内存究竟发生了什么? 假设我执行以下操作...

int main(){
    int * arr;
    arr=(int*) malloc(sizeof(int)*20);
    int i;
    for(i=0;i<20;i++) arr[i]=2*i+1;
    int * tmp=arr;
    for(i=0;i<20;i++) printf("%d ",*(tmp+i));
    printf("\n");
    free(arr);
    for(i=0;i<20;i++) printf("%d ",*(tmp+i));
    return 0;
}

我得到输出...

1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 
0 0 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 

为什么前两个条目改变了(而其他的没有改变)?

Why do the first two entries change(and the others don't)?

TL;DR undefined behavior.


一旦您在之前由 malloc() 返回的指针上调用了 free(),该指针在您的程序上下文中就不再是 有效。尝试使用它调用 undefined behavior.

谈到实际内存会发生什么,好吧,这也取决于环境。调用free()只是一种通知下层(OS/内存管理器)可以回收和重用内存的方式如果需要。没有任何强制必须清理(清零)或类似的内存位置。

mallocfreerealloc 函数管理传统上称为 "heap" 的内存区域。 mallocrealloc 选择堆的一个区域,将其标记为 "in use",return 指向内存的指针。 free returns 堆内存,供将来 mallocfree 调用使用。

free return将内存分配到堆中,并将其标记为不再被您的程序使用时,可能是它标记它的方式之一涉及在中设置位内存本身。在你的情况下,这就是你的一些数组值发生变化的原因。

(但是你当然不能依赖于此。其他实现可能会完全保留现在释放的内存。其他人可能会完全删除它。而且你的程序也有可能在尝试时崩溃在释放内存后打印出内存,因为你当然不应该这样做。)