What really happens to the memory that is allocated using malloc() after being freed? Suppose I do the following...
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;
}
I get the output...
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)?
Why do the first two entries change(and the others don't)?
TL;DR undefined behavior.
Once you've called free()
on a pointer previously returned by malloc()
, that pointer is not valid anymore in your program context. Attempt to make use of it invokes undefined behavior.
Coming to the point of what happens to the actual memory, well, that is also environment dependent. Calling free()
is just a way to inform the lower layer (OS / memory manager) that it is OK to reclaim and reuse the memory if need be. There is nothing mandated that the memory location has to be cleaned (zeroed) or alike.