Consider the following code:
#include <stdlib.h>
int main() {
int* p = (int*)malloc(10 * sizeof(int));
printf("P = 0x%p\n", p); // prints some address
p[0] = 0;
printf("P[0] = %d\n", *p); // prints 0
free(p);
printf("P = 0x%p\n", p); // prints same address
printf("P[0] = %d", *p); // prints -572662307 always
}
Why does the value of *p
change so quickly after freeing up the memory?
I know it's undefined behavior to access and change freed memory. I'm just asking how come that cell always gets garbage written into it every time?