Why it is unsafe to deal locate the memory using free( ) if it has been
allocated using new?
Ans:
This can be explained with the following example:
As against this, if we allocate memory by calling malloc( ) the constructor would not get called. Hence p holds a garbage address. Now if the memory is deal located using delete, the destructor would get called where we have tried to release the memory pointed to by p. Since p contains garbage this may result in a runtime error.
Ans:
This can be explained with the following example:
#includeThe new operator allocates memory and calls the constructor. In the constructor we have allocated memory on heap, which is pointed to by p. If we release the object using the free( ) function the object would die but the memory allocated in the constructor would leak. This is because free( ) being a C library function does not call the destructor where we have deal located the memory.
class sample {
int *p ;
public :
sample( ) {
p = new int ;
}
~sample( ) {
delete p ;
}
} ;
void main( ) {
sample *s1 = new sample ; free ( s1 ) ;
sample *s2 = ( sample * ) malloc ( sizeof ( sample
) ) ; delete s2 ;
}
As against this, if we allocate memory by calling malloc( ) the constructor would not get called. Hence p holds a garbage address. Now if the memory is deal located using delete, the destructor would get called where we have tried to release the memory pointed to by p. Since p contains garbage this may result in a runtime error.
EmoticonEmoticon