Question

In these lines of C++ code:

int * p = new int(33);
delete(p);
*p = 13;
cout << *p << endl;

The output is 13;

P points to an address on the heap initially, then I use the delete keyword to deallocate p's assigned memory address, but can still assign the memory address a value of 23; Is this the same address on the heap that p pointed to after "int * p = new int(33)" or does p point to an address on the stack after using delete(p)?

Was it helpful?

Solution

Deleting p signals to whoever manages the memory (the OS) that the underlying space is now free to be re-allocated by someone else for their own use. p, however, still points to the same memory location and can be dereferenced to obtain the value of what's in that memory -- note that since that memory may now be used by someone else, the underlying bits might be different from what they were before.

OTHER TIPS

It still points to the same address (you can tell by printing the address). You'll sometimes see people assign NULL or nullptr or 0 to a pointer after freeing the memory to ensure they don't try to try to dereference the freed memory because it doesn't get assigned null for them. This allows them to have code such as this:

if (p != nullptr)
    //do something with p, it hasn't been freed and set to nullptr

That's hard to do if it isn't set to null when it is freed, but do note that a smart pointer provides a safer, consistent alternative to the above.

The reason you're getting the correct output is undefined behaviour. It could crash, it could blow up, or it could work. I guess it chose to work.

Yes, it still points to the heap but that memory location is not stable. The OS could reclaim it any time so the value at that memory location is not guaranteed to be what you set it to.

Also, as far as I know, all dynamic memory allocation happens on the heap, not the stack. Stack is reserved for parameters and local variables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top