C++ Dynamic Memory Allocation

PREV     NEXT

What is memory allocation?

The memory in C++ can be allocated in two ways:

Static Memory Allocation:

In static memory allocation the memory is allocated for the named variables by the compiler. The size and data type of the storage must be known at the compile time.

Dynamic Memory Allocation:

In the dynamic memory allocation the memory is allocated during run time. The space which is allocated dynamically usually placed in a program segment which is known as heap. In this, the compiler does not need to know the size in advance.

What is Dynamic Memory Allocation?

  • In C++, dynamic memory allocation means performing memory allocation manually by programmer. It is allocated on the heap and the heap is the region of a computer memory which is managed by the programmer using pointers to access the memory.
  • The programmers can dynamically allocate storage space while the program is running but they cannot create a new variable name.

Dynamic memory allocation requires two criteria:

  • Creating the dynamic space in memory.
  • Storing its address in a pointer

What is the use of Dynamic Memory Allocation?

  • Dynamic Memory Allocation is to allocate memory of variable size which is not possible with compiler allocated memory except variable length arrays.
  • The most important use of dynamic memory allocation is the flexibility as the programmers are free to allocate and deallocate memory whenever we need and when we don’t.

How memory is allocated and deallocated in C++?

In C++, we can allocate and deallocate memory by using two operators new and delete operator respectively which perform the task of allocating and deallocating the memory. Let us have a discussion on these two operators.

New Operator

The new operator signifies a request for memory allocation on the heap and if the sufficient memory is available then the new operator initializes the memory and returns the address of the newly allocated variable and initialized memory to the pointer variable.

Syntax:

pointer-variable = new data type;

Here, the pointer-variable is the pointer of type data type. Data type could be any built in data type including array or any user defined data type including class and structure.

Delete Operator

The delete operator is used to deallocate the memory created by new operator at runtime. Once the memory is no longer needed it should be free so that the memory becomes available again for other request of dynamic memory.

Syntax:

delete pointer-variable;

In the delete operator the pointer-variable is the pointer that points to the data object created by the new.

Let us have a look at the example:

PREV     NEXT


Share this website !!!
Facebook Twitter Linkedin