Categories
Computer Science / Information Technology Language: C++

Dynamic memory allocation in C++

Despite having classes like vectors in C++, the knowledge of dynamic memory allocation is necessary as the vectors use this in the background and abstract these details to the programmer. Relatively, C++ dynamic memory allocation is simpler than C. As opposed to C’s 4 memory allocation functions (malloc(), calloc(), realloc() and free()), C++ has only 2 keywords (new and delete) to deal with dynamic memory allocation.

Memory handling using new and delete

The new keyword in C++ is conceptually equivalent to calloc() function in C. It allocates the memory from the heap and returns a pointer to the starting of the newly allocated memory.

The delete keyword can be used to deallocate the allocated memory in the heap by the new keyword. It is always recommended to deallocate the memory after use. If not done, memory leaks happen and eventually the application crashes.

For a single entity

  1. The syntax for allocation:
<data_type> *variable_name = new <data_type>;
// Where the data_type is user-defined or C++ built-in.
  1. Explanation:
    • This allocates a single block of memory in heap with a size equivalent to storing one element of the given data_type.
    • The data initialised by default is garbage in relatively older compilers. Hence it is always safer to initialise data manually.
  2. The syntax for deallocation:
delete variable_name;
  1. Example
#include <iostream>
#include <string>
using namespace std;
int main() {
    int *ptr_val = new int;
    cout << ptr_val;
    delete ptr_val;
    return 0;
}

Output: 0x562f303f7eb0

Allocate storage for an array

  1. The syntax for allocation:
<data_type> *variable_name = new <data_type>[size];

Where,

  • The data_type is user-defined or C++ built-in.
  • The size is the number of locations to be allocated. 
  1. Explanation:
    • This allocates a series of size number of contiguous blocks of memory in the heap.
    • The data initialised by default is garbage in relatively older compilers. Hence it is always safer to initialise data manually.
  1. The syntax for deallocation:
delete [] variable_name;
  1. Example
#include <iostream>
#include <string>
const size_t size = 4;
using namespace std;
int main() {
    int *ptr_val = new int[size];
    int val = 1;
    for (size_t i = 0 ; i < 4 ; i++)
        ptr_val[i] = val++;
    for (size_t i = 0 ; i < 4 ; i++)
        cout << ptr_val[i] << " ";
    delete [] ptr_val;
    return 0;
}

Output: 1 2 3 4

Leave a Reply

Your email address will not be published. Required fields are marked *

You cannot copy content of this page