What happens when I do something like
int * ptr = new int;
*ptr = 5;
// ... do some stuff here
ptr = new int;
// ... reuse ptr to do some other stuff
as opposed to
int * ptr1 = new int;
*ptr1 = 5;
// ... do some stuff here
delete ptr1;
int * ptr2 = new int;
// ... use ptr2 now
????
Does the same thing happen at the hardware level? In other words, in the first case, does ptr = new int;
move on from its previous pointer/value pair, and what happens to those old values? Do they get replaced, do they just float around somewhere, etc.?
Double free errors occur when free() is called more than once with the same memory address as an argument. Calling free() twice on the same value can lead to memory leak.
It merely allocates new space and returns a pointer to it. Then that new pointer is assigned to newPtr , which erases the old value that was in newPtr .
If we free the same pointer two or more time, then the behavior is undefined. So, if we free the same pointer which is freed already, the program will stop its execution.
The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. which means that a later call to malloc (or something else) might re-use the same memory space. As soon as a pointer is passed to free() , the object it pointed to reaches the end of its lifetime.
Your int *ptr
is just a variable that stores an address, nothing more.
After your first int * ptr = new int;
, it contains the address to a dynamically allocated integer. After your second int * ptr = new int;
, it contains the address to another dynamically allocated integer.
What happens then is nothing special, the only thing is that you didn't call delete
so the memory allocated for the first integer will never be freed. There's nothing to keep track of it, its address isn't stored anywhere, and so it will keep being useless allocated space until the program ends.
In the first example, the pointer is overwritten, but the object it pointed to still exists and is "floating around" somewhere. This causes memory leaking.
If this happens in a frequently used function or in a loop, you could easily exhaust your memory, storing values that you can't nor won't access any more.
Leaking is in fact a very common error. A good practice is to avoid it by using smart pointers such as shared_ptr
. These keep track of a usage count, and free the object automatically if it's no longer used. For example:
shared_ptr<int> ptr = make_shared<int>(); // allocate an int
*ptr = 5;
// ... do some stuff here
ptr = make_shared<int>(); // the old object is no longer used so deleted automatically
// ... reuse ptr to do some other stuff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With