Until today I lived in belief that calling free()
on memory space releases it for further allocation without any other modifications. Especially, considering this SO question that clearly states that free()
DOESN'T zero out memory.
Yet, let's consider this piece of code (test.c):
#include<stdlib.h>
#include<stdio.h>
int main()
{
int* pointer;
if (NULL == (pointer = malloc(sizeof(*pointer))))
return EXIT_FAILURE;
*pointer = 1337;
printf("Before free(): %p, %d
", pointer, *pointer);
free(pointer);
printf("After free(): %p, %d
", pointer, *pointer);
return EXIT_SUCCESS;
}
Compiling (both GCC and Clang):
gcc test.c -o test_gcc
clang test.c -o test_clang
Result:
$ ./test_gcc
Before free(): 0x719010, 1337
After free(): 0x719010, 0
$ ./test_clang
Before free: 0x19d2010, 1337
After free: 0x19d2010, 0
Why is it so? Was I living in a lie all this time or did I misunderstand some basic concepts? Or is there a better explanation?
Some technical info:
Linux 4.0.1-1-ARCH x86_64
gcc version 4.9.2 20150304 (prerelease) (GCC)
clang version 3.6.0 (tags/RELEASE_360/final)
question from:
https://stackoverflow.com/questions/30683519/is-free-zeroing-out-memory 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…