Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding heap corruption

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?

like image 743
Green goblin Avatar asked Dec 12 '22 01:12

Green goblin


2 Answers

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
}  
like image 181
Ryan Avatar answered Dec 14 '22 14:12

Ryan


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.

like image 37
Chris Dargis Avatar answered Dec 14 '22 13:12

Chris Dargis