C++ Memory Management

C++ Memory Management

Unlike managed languages like Java or Python, C++ gives you direct control over memory allocation and deallocation. While this gives you high performance, it also requires you to carefully manage memory.

Dynamic Memory Allocation

Sometimes you don't know how much memory you will need until runtime. You can dynamically allocate memory using the new keyword.

Example

int* ptr = new int; // Dynamically allocate an integer
*ptr = 100;
cout << *ptr; 

You can also allocate arrays dynamically:

Example

int* arr = new int[5]; // Allocates memory for 5 integers

Deallocating Memory

When you dynamically allocate memory using new, you must free it when you are done to prevent memory leaks. You do this with the delete keyword.

Example

delete ptr; // Frees the memory allocated for the integer

For dynamically allocated arrays, use delete[]:

Example

delete[] arr; // Frees the memory for the array

Best Practices

  1. Every new needs a delete.
  2. Avoid using pointers that point to deleted memory (known as dangling pointers). Set them to nullptr after deletion:

Example

delete ptr;
ptr = nullptr;

Mastering memory management is the key to becoming an expert C++ developer!


Exercise

?

Which keyword is used to free dynamically allocated memory in C++?