Home > Article > Backend Development > Stack vs. Heap: Where Do C Objects Live?
Object Creation: Stack vs. Heap
When creating an object in C , your choice of syntax affects whether it resides on the stack or the heap. While this concept isn't explicitly referenced in the provided code snippets, it's important to understand for effective memory management.
Object Creation on the Stack
The code Object o; creates an object on the stack. The object's storage duration is automatic, meaning it exists within the scope where it was declared. When the scope ends, so does the object.
Object Creation on the Heap
To allocate an object on the heap, we use Object * o; o = new Object(). This creates a pointer on the stack that points to an object on the heap. The object's storage duration is dynamic, allocated at runtime, and must be manually deallocated (via delete) to avoid memory leaks.
Creating a Pointer and Storing a Heap Object
In the code Object * o; o = new Object(), the pointer o is created on the stack, but it points to an object created on the heap. This allows us to access the heap object indirectly through the pointer.
Global Objects
Global variables reside in a different memory region outside of the stack and heap. When Object * o is declared as a global variable, the pointer itself is stored in this global memory area.
Storage Duration
In C , storage duration determines object allocation:
The above is the detailed content of Stack vs. Heap: Where Do C Objects Live?. For more information, please follow other related articles on the PHP Chinese website!