프로그래밍/C++ 문법

Dynamic Memory Allocation in C++

studylida 2023. 2. 6. 21:00

In this article, we will explore the different ways of performing dynamic memory allocation in C++, including the use of malloc(), the new and delete operators, and the new[] operator. We will also discuss 2D and multi-dimensional arrays, and provide code examples to illustrate the concepts.

malloc()

The malloc() function is part of the standard C library, and is used to dynamically allocate memory in C++ programs. The syntax for using malloc() is as follows:

void* malloc(size_t size);

Here, size is the number of bytes to be allocated, and the function returns a pointer to the first byte of the newly allocated memory.

 

Here's a code example that demonstrates how to use malloc() to dynamically allocate memory for an array of integers:

#include <iostream>
#include <cstdlib>

int main() {
    int n = 5;
    int *p = (int*)malloc(n * sizeof(int));
    if (p == nullptr) {
        std::cout << "Error: Unable to allocate memory." << std::endl;
        return 1;
    }
    // Use the dynamically allocated memory
    for (int i = 0; i < n; i++) {
        p[i] = i * 2;
    }
    // Display the contents of the array
    for (int i = 0; i < n; i++) {
        std::cout << p[i] << " ";
    }
    std::cout << std::endl;
    // Deallocate the memory
    free(p);
    return 0;
}

The output of this program is:

0 2 4 6 8

It is important to note that malloc() does not call the constructor for the objects being allocated, and as a result, the objects are not automatically initialized. To avoid potential problems, it is recommended to use the new operator instead of malloc() when working with C++ programs.

new operator

The new operator is the C++ equivalent of malloc(), and is used to dynamically allocate memory in C++ programs. The syntax for using the new operator is as follows:

new type;
new type[size];

Here, type is the data type of the object to be allocated, and size is the number of objects to be allocated (for arrays). The new operator returns a pointer to the first byte of the newly allocated memory.

Here's a code example that demonstrates how to use the new operator to dynamically allocate memory for an array of integers:

#include <iostream>

int main() {
    int n = 5;
    int *p = new int[n];
    // Use the dynamically allocated memory
    for (int i = 0; i < n; i++) {
        p[i] = i * 2;
    }
    // Display the contents of the array
    for (int i = 0; i < n; i++) {
        std::cout << p[i] << " ";
    }
    std::cout << std::endl;
    // Deallocate the memory
    delete[] p;
    return 0;
}

The output of this program is he same as the malloc() example:

0 2 4 6 8

The main advantage of using the new operator over malloc() is that the new operator calls the constructor for the objects being allocated, allowing for automatic initialization of the objects.

delete operator

The delete operator is used to deallocate memory that has been dynamically allocated using the new operator. The syntax for using the delete operator is as follows:

delete pointer;
delete[] pointer;

Here, pointer is a pointer to the dynamically allocated memory. The first form of the delete operator is used to deallocate a single object, while the second form is used to deallocate an array of objects.

It is important to match each call to new with a corresponding call to delete, to avoid memory leaks in your programs.

2D and Multi-Dimensional Arrays

Dynamic memory allocation is especially useful when working with 2D and multi-dimensional arrays, which can allocated dynamically using the new[] operator. The basic idea is to allocate an array of pointers to arrays of the desired type, and then use each pointer to dynamically allocate an array of the desired type.

 

Here's an example of how to allocate and use a 2D array of integers:

#include <iostream>

int main() {
    int rows = 3;
    int cols = 4;
    int **p = new int*[rows];
    for (int i = 0; i < rows; i++) {
        p[i] = new int[cols];
    }
    // Use the dynamically allocated memory
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            p[i][j] = i * cols + j;
        }
    }
    // Display the contents of the 2D array
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            std::cout << p[i][j] << " ";
        }
        std::cout << std::endl;
    }
    // Deallocate the memory
    for (int i = 0; i < rows; i++) {
        delete[] p[i];
    }
    delete[] p;
    return 0;
}

The output of this program is:

0 1 2 3
4 5 6 7
8 9 10 11

 

Here's an example of how to allocate and use a 3D array of integers:

#include <iostream>

int main() {
    int x = 2;
    int y = 3;
    int z = 4;
    int ***p = new int**[x];
    for (int i = 0; i < x; i++) {
        p[i] = new int*[y];
        for (int j = 0; j < y; j++) {
            p[i][j] = new int[z];
        }
    }
    // Use the dynamically allocated memory
    for (int i = 0; i < x; i++) {
        for (int j = 0; j < y; j++) {
            for (int k = 0; k < z; k++) {
                p[i][j][k] = i * y * z + j * z + k;
            }
        }
    }
    // Display the contents of the 3D array
    for (int i = 0; i < x; i++) {
        for (int j = 0; j < y; j++) {
            for (int k = 0; k < z; k++) {
                std::cout << p[i][j][k] << " ";
            }
            std::cout << std::endl;
        }
        std::cout << std::endl;
    }
    // Deallocate the memory
    for (int i = 0; i < x; i++) {
        for (int j = 0; j < y; j++) {
            delete[] p[i][j];
        }
        delete[] p[i];
    }
    delete[] p;
    return 0;
}

The output of this program is:

0 1 2 3
4 5 6 7
8 9 10 11

12 13 14 15
16 17 18 19
20 21 22 23

In conclusion, dynamic memory allocation is a powerful feature of C++ that allows you to allocate memory at runtime, providing greater flexibility and control over your programs. Whether you're working with arrays or other data structures, understanding how to use the malloc(), new, delete, and new[] operators is an essential part of any C++ programmer's toolkit.