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 allocatingpon the heap so you have to take care of deleting it at the end. Between thechar *panddelete, indo some stuff with p, the code could throw an exception andpis leaked.When using
char p[5], you’re allocatingpon the stack that way you don’t have to take care ofdeleteand even if the code throws an exception, you’re safe.