Wednesday, January 12, 2011

C++ : New and Malloc


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);

Notes:
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);



1 comment:

  1. Standard C++ supports placement new operator, which constructs an object on a pre-allocated buffer (memory, which is already alocated). This is useful when building a memory pool, a garbage collector or simply when performance and exception safety are paramount (there's no danger of allocation failure since the memory has already been allocated, and constructing an object on a pre-allocated buffer takes less time):
    Example :
    void placement() {
    char *buf = new char[1000]; //pre-allocated buffer
    string *p = new (buf) string("hi"); //placement new
    string *q = new string("hi"); //ordinary heap allocation
    }

    ReplyDelete