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.
The malloc
, free
, and realloc
functions manage an area of memory traditionally called the "heap". malloc
and realloc
pick an area of the heap, mark it as being "in use", and return a pointer to the memory to you. free
returns memory to the heap, for use by future malloc
and free
calls.
When free
returns memory to the heap, and marks it as being no longer in use by your program, it may be that one of the ways it marks it involves setting bits in the memory itself. In your case, that's why some of your array values changed.
(But you can't depend on this, of course. Other implementations might have left the now-freed memory completely unchanged. Others might have erased it entirely. And it's also possible that your program could have crashed when trying to print out the memory after freeing it, since of course you're not supposed to do that.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.