Course Content
C++ Smart Pointers
C++ Smart Pointers
Dynamic memory allocation
There are two types of memory available for use: stack and heap. Stack memory is limited in size and is well-suited for small, short-lived variables that are not needed beyond their scope. When a variable stored on the stack goes out of scope, it is automatically destroyed.
stack_allocated
// Creates an integer variable on the stack int stack_int = 42;
However, when you need memory that persists longer than its scope, or requires more space, you turn to the heap. The heap is a much larger pool of memory where your program can request memory at runtime. This is typically done using the new
keyword:
heap_allocated
// create an integer on the heap int* heap_int = new int;
The tricky thing about heap memory is that it is not automatically released. It's the developer's responsibility to deallocate it when they are done. For every new
, there must be a corresponding delete
.
free_pointer
// Explicitly deletes the integer on the heap delete heap_int;
Memory Leaks
When you introduce pointers into your code, you enter the realm of manual memory management. Manual memory management requires you to release the memory when it's no longer needed. It can lead to common pitfalls: memory leaks and dangling pointers.
Memory leaks typically occur when you forget to deallocate memory. Such memory remains reserved, causing your program to lose memory over time.
memory_leak
running = true while (running) { int* p_int = new int; }
Dangling Pointers
Dangling pointers occur when a pointer continues to point to a memory that's been deallocated. It's like having a treasure map that leads you to a place (memory address) where the treasure (data) has already been taken (destroyed).
main
#include <iostream> int main() { int* ptr = new int; // dynamically allocate an integer *ptr = 42; // assign a value to the allocated memory std::cout << *ptr << std::endl; // This will output 42 delete ptr; // deallocate the memory std::cout << *ptr << std::endl; // ptr is a dangling pointer! }
Trying to access a pointer after calling delete
on it, which deallocates the memory it was pointing to. After deletion, the pointer becomes a dangling pointer, as it still holds the address to a memory that no longer exists.
Accessing a dangling pointer can lead to unpredictable behavior or even crashes, as the memory it points to is no longer valid.
Thanks for your feedback!