Background:
In C++, memory management is fundamental; the language gives programmers full control for efficiency. Initially, only the concepts of "stack" and "heap" existed as areas for dynamic and automatic memory allocation.
Problem:
The choice of where to place a variable determines its lifespan, accessibility, allocation and deallocation speed, as well as risks (leaks, stack corruption, fragmentation).
Solution:
Stack allocation is used for local variables with known lifetimes. Heap allocation is for objects that require dynamic lifetimes or large memory volumes. It is recommended to minimize manual heap management, preferring stack usage and using smart pointers for dynamic memory.
Code example:
// Stack allocation int a = 5; // Heap allocation int* b = new int(10); // Working with a smart pointer #include <memory> auto ptr = std::make_unique<int>(15);
What happens if you return a pointer to a local variable from a function?
It results in undefined behavior: after exiting the function, the memory "is freed" (actually, the stack is not cleared, but the data may be overwritten).
Bad code example:
int* foo() { int a = 42; return &a; // incorrect! }
Can memory allocated on the stack leak?
No, stack memory is always released automatically upon exiting the visibility scope — only a stack overflow occurs, not a leak.
Is it always enough to use delete to free dynamic memory?
No, smart pointers (std::unique_ptr, std::shared_ptr) are much more frequently used to avoid forgotten deletes and double deletions.
Negative case:
A developer used new for all temporary objects but forgot to release them — over time, memory leaks occurred in large applications.
Pros: initially fast and convenient Cons: unstable programs, memory growth, crashes
Positive case:
Using local variables and smart pointers for temporary and service objects. No explicit delete, everything is released automatically.
Pros: no leaks, reliability Cons: requires understanding of modern memory management approaches