Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C++ Memory: new and delete

Local variables are created when a function starts and destroyed when it returns; they live on the stack. Sometimes an object must outlive the function that creates it, or its size is only known while the program runs. Such objects are created on the heap with new, and must be destroyed with delete.

new and delete for one object

#include <iostream>

int main() {
    int* p = new int(42);     // an int on the heap
    std::cout << *p << "\n";
    *p += 8;
    std::cout << *p << "\n";
    delete p;                 // give the memory back
    p = nullptr;              // p no longer points anywhere
    return 0;
}
Output
42
50

new[] and delete[] for arrays

An array created with new[] must be freed with delete[], not plain delete:

#include <iostream>

int main() {
    int n = 5;
    int* squares = new int[n];
    for (int i = 0; i < n; i++) squares[i] = (i + 1) * (i + 1);
    for (int i = 0; i < n; i++) std::cout << squares[i] << " ";
    std::cout << "\n";
    delete[] squares;
    return 0;
}
Output
1 4 9 16 25 

The rules

  • Every new needs exactly one delete, and every new[] exactly one delete[].
  • Forgetting delete is a memory leak: the memory stays reserved until the program ends. With Safe mode on, the editor reports leaks when the program finishes.
  • Using memory after delete (a dangling pointer) or deleting twice is a serious bug. Setting the pointer to nullptr after delete makes such mistakes easier to catch.
  • If new cannot find memory, it throws a std::bad_alloc exception.

Why modern C++ rarely writes delete

Getting every delete right is hard, especially when a function can return early or an exception is thrown. Modern C++ uses classes that manage memory for you:

  • std::vector instead of new[] for arrays whose size is known at run time;
  • std::string instead of character arrays;
  • std::unique_ptr and std::shared_ptr (see Smart Pointers) for single objects.
#include <iostream>
#include <vector>

int main() {
    int n = 5;
    std::vector<int> squares(n);      // the vector owns its memory
    for (int i = 0; i < n; i++) squares[i] = (i + 1) * (i + 1);
    for (int s : squares) std::cout << s << " ";
    std::cout << "\n";
    return 0;                          // freed automatically
}
Output
1 4 9 16 25 

Learn new and delete to understand what happens underneath, then let the standard library do the work.

Practice exercises

  1. Ask the user for a size, create an array of that many double values with new[], fill it, print the average and delete[] it.
  2. With Safe mode on, remove the delete[] and read the leak report.
  3. Rewrite exercise 1 with a std::vector and compare the two versions.