C++
03-Dynamic Memory

Memory

The memory available to an application at run-time consists of static memory and dynamic memory

Static Memory

  • The memory that the operating system allocates for the application at load time is called static memory.
  • Static memory lasts the lifetime of the application
  • The linker determines the amount of static memory used by the application

Dynamic Memory

  • The operating system provides dynamic memory to an application at run-time upon request
  • Dynamic memory is allocated on the heap (a region of memory that is not managed by the operating system)

lifetime

  • The lifetime of dynamic memory is determined by the application
  • The application is responsible for releasing the memory when it is no longer needed
  • If the application fails to release the memory, it results in a memory leak

Dynamic Memory Allocation/Deallocation

  • The new operator is used to allocate memory on the heap
  • The delete operator is used to release memory allocated by new
  • The address of the allocated memory is stored in a pointer variable (static memory)
  • Allocated memory must be deallocated within the scope of the pointer that holds its address
#include <iostream>
using namespace std;
 
int main() {
    // allocate memory for an integer
    int* p = new int;
    *p = 10;
    cout << *p << endl;
 
    // release memory
    delete p;
 
    return 0;
}

Memory Leaks

  • A memory leak occurs when the application fails to deallocate memory that is no longer needed
    • The pointer to dynamic memory goes out of scope before the application deallocates that memory
    • The pointer to dynamic memory changes its value before the application deallocates the memory starting at the address stored in that pointer