Dynamic Memory Allocation in C++: A Complete Guide

In this lesson, you will learn

  • Dynamic Memory Allocation(DMA)
  • Dynamic Memory Management in C
  • Example
  • Dynamic Memory Management in C++
  • Example

Dynamic Memory Allocation(DMA)

Dynamic memory allocation allows you to allocate and deallocate memory for objects at runtime, rather than at compile-time.

DMA is particularly useful when you don’t know in advance how much memory space is required for an array or object.

In C, malloc() and calloc() functions are used to allocate memory dynamically at run time and the free() function is used to deallocate memory.

In C++, dynamic memory management is often done using the new and delete unary operators.

Dynamic Memory Management in C

In C, dynamic memory management is primarily achieved using the following library functions:

1. malloc(): Allocates a block of memory of a specified size and returns a pointer to the first byte of the block.

void* malloc(size_t size);

2. calloc(): Allocates a block of memory for an array of elements, initializes all bytes to zero, and returns a pointer to the first byte of the block.

void* calloc(size_t num_elements, size_t element_size);

3. realloc(): Changes the size of the previously allocated memory block, possibly moving it to a new location in memory.

void* realloc(void* ptr, size_t new_size);

4. free(): Deallocates a previously allocated memory block.

void free(void* ptr);

Example: Dynamic Memory Allocation in C

//DMAinCEx1.
#include <stdio.h>
#include <stdlib.h>

int main() {
    // Allocating memory for a single integer
    int* dynamicInt = (int*)malloc(sizeof(int)); 
    
    if (dynamicInt == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    *dynamicInt = 42; // Assigning a value to 
                      // the dynamically allocated integer
    printf("Value: %d\n", *dynamicInt);

    free(dynamicInt); // Deallocating the dynamically allocated memory

    return 0;
}

Output

Value: 42

Dynamic Memory Allocation in C++

In C++, dynamic memory management is often done using the new and delete operators.

Additionally, C++ offers higher-level abstractions through classes, constructors, and destructors.

Note: A data object created inside a block using new will remain in existence until it is destroyed using the delete operator. Thus, the lifetime of an object is directly under control and totally unrelated to the block structure of the program.

The ‘new’ operator

  • The new operator is used to allocate memory for a single object or an array of objects on the heap.
  • It returns a pointer to the allocated memory.

Syntax

data_type* pointer_name = new data_type;

Example

int* dynamicInt = new int; // Allocating memory for a single integer
*dynamicInt = 42; // Assigning a value to the dynamically allocated integer

We can also initialize the memory using a new operator.

Syntax

data_type* pointer_name = new data_type(value);
//Value specifies the initial value

Example

int *p= new int(10);
float *q= new float(15.50);

The new can be used to allocate memory space for any data type e.g. user-defined types such as arrays, classes, structures, etc.

Here, is the syntax for allocating an array of objects:

data_type* array_name = new data_type[size];

Example

int size = 5;
int* dynamicIntArray = new int[size]; // Allocating memory for an array of integers
for (int i = 0; i < size; i++) {
    dynamicIntArray[i] = i * 10; // Initializing the array elements
}

The ‘delete’ operator

  • The delete operator is used to deallocate memory that was previously allocated using new.
  • It releases the memory on the heap, preventing memory leaks.

Syntax

delete pointer_name;

Example

delete[] array_name;

Example: Dynamic Memory Allocation in C++

//DynamicMemoryEx1.cpp
#include <iostream>
using namespace std;

class MyClass {
public:
    MyClass(int value) : data(value) {
        cout << "Constructor called with value " << data <<endl;
    }

    ~MyClass() {
        cout << "Destructor called for value " << data <<endl;
    }

    void display() {
        cout << "Value: " << data <<endl;
    }

private:
    int data;
};

int main() {
    // Allocating an object with a constructor
    MyClass* dynamicObj = new MyClass(42); 
    dynamicObj->display();
    
    delete dynamicObj; // Deallocating the object with a destructor

    return 0;
}

Output

Constructor called with value 42
Value: 42
Destructor called for value 42


End of the Lesson…Happy Learning

Student Ratings and Reviews

There are no reviews yet. Be the first one to write one.

Submit a Review

Spread the love
0
1