Posted By:
2 Jul, 2013 6:53 am PDT

Dynamic memory allocation in C++

How can we allocate memory dynamically?

Dynamic allocation is one of the way for using memory provided by the C/C++ standard. To accomplish this in C the malloc function is used and the new keyword is used for C++. Both of them perform an allocation of a contiguous block of memory, malloc taking the size as parameter:

int *data=new int

int *data=(int*)malloc(sizeof (int));     //sizeof is used for portability


This memory block can be used whenever needed during the program execution or until explicitly deallocating it, unlike the automatic memory which is available only inside the function or block of instructions where it was declared. Allowing a program to allocate dynamic storage every time it needs more until the program stops can cause it eventually to run out of available space. To prevent this behavior C++ provides the delete operator with the job of recycling a segment of memory allocated with new:

delete (data);

In C we free(), which behaves in same manner as that of delete()

free (data);

If the allocated dynamic variable is not deleted when it is unnecessary then it will lead to memory leak. Memory leaks are very dangerous because it mean the system runs out of memory.

Was it useful?  

Please login to reply to this problem.