0
#include<iostream>


using namespace std;


int main()
{

int *ptr;
int n=5,i;
ptr=(int*)malloc(n*sizeof(int));
if(ptr==NULL){
    cout<<"Memory not allocated"<<endl;
    return 0;
}
else{
    cout<<"Memory allocated"<<endl;
     for(i=0;i<n;i++){
    ptr[i]=i+1;

}
for(i=0;i<n;i++){
    cout<<ptr[i]<<" ";

}
free(ptr);
cout<<"\nMemory Freed\n";


 for(i=0;i<n;i++){
    cout<<ptr[i]<<" ";

}
}


return 0;
}

**OUTPUT:

Memory allocated

1 2 3 4 5

Memory Freed

18682760 18677952 3 4 5**

Why is the OUTPUT after free(ptr) is some numbers. I'm new to dynamic programming so I experimented with malloc() and calloc() when i observed this. I thought after using free(ptr) i thought the array will be NULL but it still contains some values and when i run the program again the value after free(ptr) changes. Can anyone explain ?

  • You've free'd the memory for `ptr`. What do you expect it to contain? Even accessing it is undefined behavior. – cigien Jun 12 '20 at 18:17
  • _"I thought after using free(ptr) i thought the array will be NULL "_ Why did you think this? – Asteroids With Wings Jun 12 '20 at 18:17
  • Why are you accessing something you've freed? By freeing it you get rid of the memory, so you should no longer be accessing that memory. – NathanOliver Jun 12 '20 at 18:17
  • So many duplicates! Here's one: https://stackoverflow.com/q/15432123/10871073 – Adrian Mole Jun 12 '20 at 18:21
  • 3
    `free` does not set anything to null. It is your responsibility to stop using the pointer afterwards. Also, [the hotel story](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794) is applicable. – JaMiT Jun 12 '20 at 18:25
  • Note that to any one location in memory you can have an unlimited number of pointers. The C++ does not do the book-keeping to track all of these potential pointers so that they can be updated if they point to a location that has been rendered invalid because it could get very expensive very fast. In general, C++ follows a policy of not forcing a program to pay for anything it does not use, so it doesn't do anything that could slow down a program unless you explicitly ask for it. – user4581301 Jun 12 '20 at 19:39

0 Answers0