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?