This small article is for C++ beginners, who is familiar with C. The dynamic memory allocation with C will be done with Malloc library function. In C++ it will be done with an operator new. Don't be confused, new is not a function, but a operator like +.- etc.. Here I will give you some example of how we use malloc and new.
//declaring native type
int* i1 = new int;
delete i1;
int* i2 = (int*) malloc(sizeof(int));
free(i2); //declaring native type array
char** c1 = new char*[10]; // Array allocation
delete[] c1; // cleaning array allocation
char** c2 = (char**) malloc(sizeof(char)*10);
// Allocation a two dimensional array in C
free(c2);
1- Since new/delete is an operator, you can overload it.
2- There is no alternative for C function realloc , in C++.
- You can use STL containers instead of new, if a realloc required( eg. std::vector<>::resize()).
- When explicit memory management is necessary, try to use smart pointers to make it easier and safer.
- Don't use malloc() or 'new' when containers or automatic variables can do the job.
3- new will call the appropriate construction to create the object. Similarly delete will call destructor.
4- No typecasting required for new.
5- malloc() returns NULL on failure while 'new' throws an exception.
6- malloc() allocates raw memory while 'new' constructs objects in the allocated space.
eg. shape * sp=new(12);