Pointer Question

Here is a sample code of an example of pointers. Does it present a problem to free the same piece of memory twice? In this code, the address pointed to by p obtains a value of 10. Then q is assigned to point to the same address. Deleting p will free that allocated memory, so what will deleting q do?

My two guesses are that the problem will simply be ignored because it's already freed, or depending on how the heap allocator works, it might cause some form of problem. Anyone care to clear this up? :)

1
2
3
4
5
6
7
8
9
10
int *p, *q;

p = new int;
*p = 10;

q = new int;
q = p;

delete p;
delete q;


Cheers!
Last edited on
It will cause an undefined behavior. If between two deletes freed memory was allocated again, it most likely lead to crash. (And note that even if you have two deletes together like in your example, it will not stop compiler from optimising and probably allocating memory you just delete and will be deleting again)
http://stackoverflow.com/questions/14289694/why-theres-no-error-when-i-delete-twice-the-same-memory
http://stackoverflow.com/questions/2746677/what-happens-when-you-deallocate-a-pointer-twice-or-more-in-c
in practice what will usually happen in most implementations is that the program will continue to run past the deletes, and then mysteriously crash sometime later in some unrelated memory allocation.
Last edited on
If you were wanting to share pointers around, you would be best advised to implement a shared pointer mechanism, so that you can do reference counting and then only delete a pointer only when it is no longer being used.
Awesome! Thank you very much. Very helpful answers. :)
Topic archived. No new replies allowed.