Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

free won't delete memory allocated to the pointer (int array), using free twice works, why?

This is out of curiosity, I tried to find answers to my doubt on previous questions but they don't seem to have answer to it. So asking here, I just wrote a code where I am trying to allocate memory to an int pointer (to fill up an array) and scan int values to it. Once I am done with the array, I want to delete the data/memory allocated to the pointer. Although my code works fine and everything, why am I still able to see values inside int array even after freeing the pointer. Whereas, if I use free twice it throws up an error (which was expected after single use of free). Isn't this an odd behavior ? I tried it on my mac using Xcode also on codechef, same behavior, why ?

int *num=(int *)malloc(n*sizeof(int));
int i;
for(i=0;i<n;i++)
{
    scanf("%d",&num[i]);        
}    

for(i=0;i<n-1;i++){
    temp = some_function(x);        
}

free(num); 

for(i=0;i<n;i++)
{
    printf("\nnum[%d]= %d\n",i,num[i]);        
}

The above code prints values inside num[] which ideally it shouldn't.

like image 825
CodeInfinity Avatar asked Dec 02 '22 13:12

CodeInfinity


1 Answers

This is not odd, or wrong. When calling free on a pointer, you only tell the memory manager that it can re-use that portion of memory again for another malloc call. It won't erase the contents (this would take extra time with no function whatsoever). But, you can access it, because the pointer still points to a valid address. It leads to undefined behaviour though, because the memory manager could have given that memory to some other piece of code.

Calling free a second time can generate an error, because the memory manager doesn't know that pointer anymore as being valid (you just freed it!). In fact, this is undefined behaviour.

like image 104
Bart Friederichs Avatar answered Dec 05 '22 08:12

Bart Friederichs