Search code examples
memory-managementmallocfreedynamic-memory-allocationrealloc

Why free() function in C++ only deallocating 8 bytes of memory?


Possible Duplicate:
Why do I get different results when I dereference a pointer after freeing it?

Tried it in case of characters as well, what it did that after 8 values the 9th value was correct while first 8 were showing garbage value, as it is case here, first two values are showing garbage while the third is as it is. And thus only first 8 bytes are getting deallocated. Why is it so? you can also increase the number of indexes in array to check. someone please explain HOW FREE() METHOD IS WORKING HERE?

#include<iostream>
using namespace std;
#include<conio.h>
int main()
{
int *arr;
arr=(int *)malloc(sizeof(int)*3);
arr[0]=10;
arr[1]=20;
arr[2]=30;

free(arr);
for(register int i=0;i<3;i++)
{
cout<<arr[i]<<endl;
}
getch();
return 0;
}

Solution

  • free() basically only tells the runtime system "I'm done with this memory, feel free to reuse it for other things at your convenience." In other words, reading the memory after free() is entirely unsupported and may give any value whatsoever, including anything in the range from reading back exactly what you wrote to crashing your program.