Working with Dynamic Memory: Creating Objects in Heap
Lesson Introduction
Welcome! Today, we're diving into a crucial topic in C++: "Working with Dynamic Memory and Creating Objects in the Heap." Understanding dynamic memory allocation allows for more flexible memory management, especially when you need to allocate space at runtime.
In some programs, we don't know how much memory we need until runtime. For instance, if you're creating a game that loads levels, you might not know how many objects a level contains until it loads. Dynamic memory helps by letting you allocate memory exactly when you need it.
Ready? Let's get started!
Understanding Memory Management in C++
Think of your computer's memory as a bookshelf (stack) and a storage room (heap). The stack is small but quick to access, like a bookshelf where you can easily pick up your favorite book. The heap is larger but slower to access, like a storage room full of boxes.
- Stack Memory: Automatically managed and used for local variables. It's faster but limited in size.
- Heap Memory: Manually managed, useful for dynamic memory allocation. It's larger and more flexible but needs careful handling to avoid memory leaks.
Dynamic Memory Allocation with `new` and `delete`
To allocate memory in the heap, use the new keyword. This creates an object or an array of objects and returns a pointer to the memory location. One crucial thing to know is that you must deallocate the used dynamic memory. This memory will be blocked until the PC restarts if you don't do it. This problem is known as a memory leak.
Let's start with a simple example:
In this example:
new int(10): Allocates memory for an integer in the heap and initializes it with 10.int* intPtr: Stores the address of the allocated memory.*intPtr: Dereferences the pointer to access the value.delete intPtr: Deallocates the memory to prevent memory leaks.
Dynamic Arrays
Dynamic arrays are another common use of heap memory. Allocating an array dynamically allows its size to be determined at runtime.
Example:
In this example:
new int[5]: Allocates memory for an array of 5 integers in the heap.arrayPtr[i]: Accesses and manipulates elements using the pointer.delete[] arrayPtr: Deallocates the array memory to prevent memory leaks.
A memory leak is mostly dangerous when initializing dynamic arrays as they could take a lot of RAM space. Every call to new must be paired with a corresponding delete, and every new[] must be paired with a delete[].
