Search code examples
c++dynamic-memory-allocation

Why the pointer to single integer memory location can't be deleted?


#include <iostream>
using namespace std;

int main ()
{
    int myarray [10];
    int * ptr1;
    ptr1 = new (nothrow) int [10];
    cout << "ptr1 = " << ptr1 << endl;
    delete [] ptr1;
    cout << "ptr1 = " << ptr1 << endl;

    int a = 4;
    int * ptr2;
    ptr2 = &a;
    cout << "ptr2 = " << ptr2 << endl;
    delete ptr2;
    cout << "ptr2 = " << ptr2 << endl;



    return 0;
}

It outputs

ptr1 = 0x9941008
ptr1 = 0x9941008
ptr2 = 0xbfca5cd4

Questions:

1) Why the second print of ptr1 still return the same value? The memory is released but the pointer keeps the memory address value?

2) Why the second print of ptr2 doesn't output?


Solution

    • delete frees the memory, but does not change the value of the pointer. Note however, that the pointer now points to a deallocated area of memory so you should not use it until you reset it.
    • Your program surely crashes before the second print since you're trying to free a pointer which has not been allocated on the heap. You can only delete areas of memory which you have previously allocated on the heap with the new operator.