Today, on EFNet C++ Wiki in article heap corruption, I found two pieces of code.
void this_is_bad() /* You wouldn't believe how often this kind of code can be found */
{
char *p = new char[5]; /* spend some cycles in the memory manager */
/* do some stuff with p */
delete[] p; /* spend some more cycles, and create an opportunity for a leak */
}
Alternate way:
void this_is_good()
{
/* Avoid allocation of small temporary objects on the heap*/
char p[5]; /* Use the stack instead */
/* do some stuff */
}
Can someone help me in understanding why the first piece of code is not considered good?
When using char* p
, you're allocating p
on the heap so you have to take care of deleting it at the end. Between the char *p
and delete
, in do some stuff with p
, the code could throw an exception and p
is leaked.
When using char p[5]
, you're allocating p
on the stack that way you don't have to take care of delete
and even if the code throws an exception, you're safe.
void this_is_bad()
{
char *p = new char[5]; //on the heap
// What happens if I throw an unhandled exception here?
delete[] p; // I never get to delete p and it gets leaked
}
When you use the stack instead of the heap, memory is restored once the scope of the current function is lost.
When you use the new
keyword, you allocate heap memory. You must remember to delete any memory allocated with the new
keyword. If an exception is thrown after the new
keyword and before the delete
keyword, you could possibly create a memory leak because you may not resume execution at the point after where the exception was thrown.
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