Home >Backend Development >C++ >Where Do Global Variables in C Store Their Memory: Stack or Heap?

Where Do Global Variables in C Store Their Memory: Stack or Heap?

DDD
DDDOriginal
2024-12-02 09:22:11969browse

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:

  1. Code (text segment)
  2. Initialized data (data segment)
  3. Uninitialized data (bss segment)
  4. Heap
  5. Stack

Global Variable Allocation

When a global variable is declared, its memory is allocated either in the data segment or the bss segment.

  1. Data segment: Contains initialized global variables. Its size is fixed at compile time.
  2. Bss segment: Contains uninitialized global variables. Its size is also fixed at compile time, but its content is initialized to zeros by default.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn