Stack Memory
Stack memory is a limited memory space (typically around 8MB) used for storing function parameters, return addresses, and local variables. When a function is called, it creates a stack frame containing these elements.
void exampleFunction() {
int localVar = 42; // Stored in stack
}
Heap Memory
The heap (or system heap) is a global memory pool provided by the operating system for dynamic memory allocation. Programmers manually allocate and deallocate memory blocks using new and delete operators.
int* createInt() {
return new int(100); // Allocated on heap
}
Memory Leaks
Memory leaks occur when dynamically allocated heap memory isn't properly released, leading to wasted system resources and potential performance degradation.
void leakExample() {
int* ptr = new int[100]; // Allocated but never deleted
} // ptr goes out of scope, memory remains allocated
Object Lifecycles
Stack Objects
{
MyClass obj; // Constructor called
} // Destructor called automatically
Static Local Objects
{
static MyClass staticObj; // Constructor called
} // Object persists beyond scope
Global Objects
MyClass globalObj; // Constructor called before main()
int main() {
// Object exists throughout program
}
Heap Objects
{
MyClass* heapObj = new MyClass(); // Manual construction
delete heapObj; // Manual destruction required
}
Proper memory management is crucial to prevent leaks and ensure efficient resource utilization in C++ applications.