-3

I have the following code, which is not working properly...

code:

#include <iostream>
#include <new>
#define nullptr NULL
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 == nullptr)
    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 << p[n] << ", ";
    delete[] p;
    for (n=0; n<i; n++)
      cout <<"a "<< p[n] << endl;
  }
  return 0;
}

After using delete[] p; statement when I print the values of p all elements should produce garbage values because the previously allocated memory is freed... but, it produces garbage value only for the 1st 2 elements and rest of the elements print the value assigned to it... that means the total allocated memory is not freed...

  • Why it's happening?
  • How can this be fixed?
Scooter
  • 6,802
  • 8
  • 41
  • 64
MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59
  • 1
    Undefined behavior is **Undefined**. Just because you freed the memory doesn't mean that it has to be written over with garbage. In fact, since you aren't getting a segfault from trying to read memory you don't own, most likely the library is holding onto the memory in case you request it for something else. More importantly, why are you defining `nullptr` as `NULL`? – IllusiveBrian Sep 26 '14 at 07:39
  • I'll take undefined behavior for $200 Alex. – user657267 Sep 26 '14 at 07:40
  • 1
    @KhairulBasar the concepts are similar to local variables that have left scope - you may find it helpful to read over this: http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – Tony Delroy Sep 26 '14 at 07:50

2 Answers2

1

The program has undefined behaviour, Simply the memory page with the extent of the memory where the array was allocated was not discarded by OS or overwritten by other data.

There is nothing to fix. You simply may not access this memory. If your program tries to access the array after its deleting then it means that the program has a bug. To find the bug you could set the pointer to NULL. For example

delete[] p;
p = nullptr;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

It doesn't necessary mean the memory is not free. The memory starting from address p is free, but there might still be some part of previously written data. If you want these values to be different, just change them before deleting allocated memory

Maciej
  • 193
  • 2
  • 11