Dynamic Memory Allocation

new and delete operators

Interview Relevant: Memory management

Dynamic Memory

Allocate memory at runtime using new and delete.

Code Examples

Dynamic memory allocation with new/delete.

cpp
1// Single variable
2int* p = new int;       // Allocate
3*p = 42;
4delete p;               // Deallocate
5
6// With initialization
7int* p2 = new int(42);  // Allocate and init
8int* p3 = new int{42};  // C++11 uniform init
9
10// Array allocation
11int* arr = new int[10];      // Uninitialized
12int* arr2 = new int[10]();   // Zero-initialized
13int* arr3 = new int[5]{1,2,3,4,5};  // C++11
14
15delete[] arr;   // Must use delete[] for arrays!
16delete[] arr2;
17delete[] arr3;
18
19// 2D array
20int** matrix = new int*[rows];
21for (int i = 0; i < rows; i++) {
22    matrix[i] = new int[cols];
23}
24// Deallocate in reverse
25for (int i = 0; i < rows; i++) {
26    delete[] matrix[i];
27}
28delete[] matrix;
29
30// Prefer smart pointers in modern C++!

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In