0

Here i am doing dynamic memory allocation .But problem is that after deleting memory, the data is not removing from that block.Only first two blocks are deleting. Why ?

 #include <iostream>
 #include <new>
 using namespace std;

int main ()
{
  int i,n;
  int * p;
  cout << "How many numbers would you like to type? ";
  cin >> i;
  p= new (nothrow) int[i];
  if (p == 0)
    cout << "Error: memory could not be allocated";
  else
  {
    for (n=0; n<i; n++)
    {
      cout << "Enter number: ";
      cin >> p[n];
    }
    cout << "You have entered: ";
    for (n=0; n<i; n++)
      cout <<"Value= "<< p[n] << ",Address = "<<&p[n]<<endl;
    delete p;
    cout<<endl<<"After Deallocation"<<endl;
  for (n=0; n<i; n++)
      cout <<"Value= " <<p[n] << ",Address = "<<&p[n]<<endl;
}
  return 0;
}

Output of Code

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
core
  • 65
  • 1
  • 1
  • 6
  • 1
    *Only first two blocks are deleting* -- What is your definition of "deleting"? The memory isn't going to just disappear into a puff of smoke. There will be remnants of something left at those locations, and you can't determine what those remnants mean by mere inspection. – PaulMcKenzie Nov 13 '18 at 10:28
  • 2
    BTW for deleting an array, you should call `delete[] p`. – Galik Nov 13 '18 at 10:31
  • i also used it but doesn't work – core Nov 15 '18 at 15:53

1 Answers1

0

The data is deallocated, but it doesn't mean that the data values were changed.

How the data is going to be changed is not specfied. The memory may be reallocated a nanosecond after the deallocation and completely changed. Or it can stay the same until your computer stops.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
  • is there any way to check that memory has been deallocate? or how to check how many memory used in x function? – core Nov 15 '18 at 15:48
  • No, no way of checking if it's still allocated or valid, it's part of the contract of an API. Then if you want to know how much memory is used by a function (which is completely another question), then you can use massif or heaptrack. – Matthieu Brucher Nov 15 '18 at 16:31