C++ Memory Management

Static vs Dynamic Memory

  • Static memory: Allocated at compile time (e.g., variables on the stack)
  • Dynamic memory: Allocated at runtime using new

Allocating Single Variable

int* ptr = new int;
*ptr = 42;
cout << *ptr;

This creates a variable on the heap and stores 42 there.

Releasing Memory

Always free heap memory to prevent leaks:

delete ptr;

Dynamic Arrays

int* arr = new int[5];
arr[0] = 1;
arr[1] = 2;
// ...

delete[] arr;  // use delete[] for arrays

Important: Use delete[] when freeing dynamic arrays.

Memory Leaks

If you allocate memory but never deallocate it, you create a memory leak:

int* leak = new int;
// forgot to call delete leak;

This will stay in memory until the program exits.

Best Practices

  • Always initialize pointers (e.g., to nullptr)
  • Always delete what you allocate
  • Consider using smart pointers (std::unique_ptr, std::shared_ptr) in modern C++

nullptr vs NULL

nullptr is the recommended way to represent null pointers in C++11 and later:

int* p = nullptr;

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic