Home >Backend Development >C++ >Where Do Global Variables in C Store Their Memory: Stack or Heap?
Memory Allocation for Global Variables in C : Stack vs Heap
In C , when a data structure is declared globally, the question arises whether it consumes stack memory or heap memory. To understand this, we delve into the memory layout of a typical C process.
Memory Layout of a C Process
A C process typically allocates five different memory areas:
Global Variable Allocation
When a global variable is declared, its memory is allocated either in the data segment or the bss segment.
Therefore, global variables are stored in the data segment or bss segment, which are part of the static memory allocated to the program.
Example
In the given example, the array arr is a global variable of type struct AAA. It will be allocated in either the data segment or the bss segment, depending on whether it is initialized (has default values) or uninitialized (contains garbage values).
Conclusion
In summary, global data structures in C consume memory from the static memory allocated to the program, specifically from the data segment or bss segment, which are not part of either the stack or heap memory areas.
The above is the detailed content of Where Do Global Variables in C Store Their Memory: Stack or Heap?. For more information, please follow other related articles on the PHP Chinese website!