capypad
0 day streak
cpp / beginner
Snippet

Dynamic Memory Allocation with new and delete

Dynamic allocation creates memory at runtime using the new keyword. This memory lives on the heap and persists until you explicitly release it with delete. For arrays, use delete[] to free all elements. Failing to delete causes memory leaks.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;
 
int main() {
int* ptr = new int;
*ptr = 42;
cout << "Value: " << *ptr << endl;
delete ptr;
int* arr = new int[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
cout << "Array: " << arr[0] << ", " << arr[1] << ", " << arr[2] << endl;
delete[] arr;
return 0;
}
Breakdown
1
int* ptr = new int;
Allocates memory for one integer on the heap
2
*ptr = 42;
Dereferences the pointer to store a value at that memory location
3
delete ptr;
Releases the single integer's memory back to the system
4
int* arr = new int[5];
Allocates memory for an array of 5 integers
5
delete[] arr;
Releases the entire array's memory (note the brackets)
6
*ptr
Asterisk accesses the value stored at the memory address