Memory allocation lets your program get space to store data while running. Deallocation frees that space when you no longer need it, so your computer can use it for other things.
0
0
Memory allocation and deallocation in C++
Introduction
When you need to create variables or objects during the program that you don't know the size of before running.
When you want to manage memory yourself to use it efficiently.
When you create data structures like linked lists or trees that grow or shrink while the program runs.
When you want to avoid wasting memory by only using what you need.
When you want to prevent your program from crashing by cleaning up unused memory.
Syntax
C++
int* ptr = new int; // allocate memory for one int int* arr = new int[5]; // allocate memory for an array of 5 ints // use the memory *ptr = 10; arr[0] = 1; // free the memory delete ptr; // free single int delete[] arr; // free array
new gives you memory from the heap to use.
delete returns that memory back to the system.
Examples
This example shows how to allocate and free memory for a single integer.
C++
int* p = new int; // allocate one int *p = 42; // store value // later delete p; // free memory
This example shows how to allocate and free memory for an array of integers.
C++
int* arr = new int[3]; // allocate array of 3 ints arr[0] = 5; arr[1] = 10; arr[2] = 15; // later delete[] arr; // free array memory
Sample Program
This program shows how to allocate memory for a single integer and an array, use them, then free the memory to avoid waste.
C++
#include <iostream> int main() { int* number = new int; // allocate memory for one int *number = 100; // store value int size = 3; int* array = new int[size]; // allocate array for (int i = 0; i < size; i++) { array[i] = i * 10; // fill array } std::cout << "Number: " << *number << "\n"; std::cout << "Array values: "; for (int i = 0; i < size; i++) { std::cout << array[i] << " "; } std::cout << "\n"; delete number; // free single int delete[] array; // free array return 0; }
OutputSuccess
Important Notes
Always use delete for memory allocated with new to avoid memory leaks.
Use delete[] to free arrays allocated with new[].
Failing to free memory can cause your program to use too much memory and slow down or crash.
Summary
Memory allocation reserves space for data during program run.
Memory deallocation frees that space when done.
Use new and delete carefully to manage memory safely.