CurriculumDynamic Memory Allocation

Dynamic Memory Allocation

Dynamic Memory Allocation is the process of requesting memory from the Operating System at <strong>runtime</strong>. You use this when you don't know how much memory you need when writing the code (e.g. user inputting the size of an array), or when you need data to survive outside the scope of a function.

01The 'new' Keyword

To request memory on the Heap, use new followed by the type. It returns a pointer to the newly allocated memory.

You can optionally initialize it by passing a value in parentheses.
main.cpp
Loading...
Terminal
Waiting for execution...
Visualizer
Run code to see stack and heap.

02The 'delete' Keyword

When you are done with dynamic memory, you must return it to the OS using the delete keyword.

Deleting the pointer does not destroy the pointer variable itself (it still lives on the stack). It destroys the Heap memory it points to.
main.cpp
Loading...
Terminal
Waiting for execution...
Visualizer
Run code to see stack and heap.

03Dynamic Arrays (new[])

Often, you need an array but you don't know the size until the user types it in. The Stack requires array sizes to be known at compile time. The Heap doesn't!

Use new Type[size] to allocate a dynamic array.
main.cpp
Loading...
Terminal
Waiting for execution...

04Deleting Arrays (delete[])

If you used new[] to create an array, you must use delete[] to free it.

If you just use delete, it will only free the first element of the array, causing a massive memory leak!
main.cpp
Loading...
Terminal
Waiting for execution...

05std::bad_alloc (Pro Tip)

What happens if you ask for memory, but the OS is completely out of RAM? The new operator will fail and throw an exception called std::bad_alloc.

For safety-critical systems, you can use new (std::nothrow) which returns a nullptr instead of crashing, allowing you to handle the error gracefully.
main.cpp
Loading...
Terminal
Waiting for execution...
← Back to Curriculum