C++ Programming (Memory allocation/deallocation)

When programming in C/C++, one of the important things to take note of is memory allocation and deallocation. Without proper memory allocation, you would most probably get into run-time error during execution. Without proper memory deallocation, you would have memory leaks.

In C, you use malloc( ) and free() for memory allocation/deallocation. In C++, you use new and delete.

Example of memory allocation in C:

TypeName *typeNamePtr;
typeNamePtr = malloc(sizeof(TypeName));
free(typeNamePtr);

Example of memory allocation/deallocation in C++:

int* pnPtr=0; char* pcChar=0;
pnPtr = new int; //Allocate space for pointer variable
pcChar = new char[20] //Allocate space for 20 char.
delete pnPtr;
delete[ ] pcChar;

Things to note:
• Unlike new, malloc does not provide any method of initializing the block of memory allocated.
• Also, new/delete automatically invokes the constructor/destructor
• Do not mix new with free and malloc with delete.