example1_heap_allocation_deallocation.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int main() {
    // Allocate an integer on the heap
    int* pNumber = new int;

    // Assign a value
    *pNumber = 42;

    std::cout << "Value: " << *pNumber << std::endl;

    // Deallocate the memory
    delete pNumber;

    // Avoid dangling pointer
    pNumber = nullptr;

    return 0;
}
Back to heap