
What is a Variable?
A variable can generally be classified as shown in the figure below:

The focus of this section is to help everyone understand the memory model of the stack, temporarily ignoring the case of static variables, and we agree on the following:
“Global variables” are simply assumed to be “ordinary global variables”;
“Local variables” are simply assumed to be “ordinary local variables”.
How to Determine Global and Local Variables?
Simply put, a global variable is defined outside of functions, while a local variable is defined inside functions. The following example clearly illustrates how to determine global and local variables:
unsigned char a; // Defined outside of the function, so it is a global variable.
void main() // Main function
{
unsigned char b; // Defined inside the function, so it is a local variable.
b=a;
while(1)
{
}
}
Memory Model of Global and Local Variables
The memory of a microcontroller consists of ROM and RAM. ROM stores the instructions and some unchangeable constant data in the microcontroller’s program, while RAM holds variable data that can be changed;
In other words, both global and local variables are stored in RAM, but although they are both in RAM, there is a significant difference in the memory model between global and local variables.
Thus, there are two different RAM areas: the global data area occupied by global variables and the stack occupied by local variables.
What is the Essential Difference in Their Memory Models?
The global data area is like your own room at home, which is unique. The address of a room can only be occupied by you (assuming you are single), and it is permanent (sorry). Therefore, each global variable has a unique corresponding RAM address, which cannot be duplicated.
The stack is like a guesthouse, where different people stay every night, and each person’s stay has a time limit, not permanent. The address of a room may be occupied by different people throughout the year; it is not unique.
The global variable in the global data area has permanent ownership, while the local variable in the stack can only temporarily reside in the guesthouse, with a non-unique address and a time limit.
The stack is shared among all local variables in the functions within the program. When a function is called, each local variable within that function is assigned to a certain RAM address in the stack. After the function call ends, that local variable becomes invalid.
Thus, the corresponding stack‘s RAM space is reclaimed for the local variables of the next called function.
Using the “Guesthouse” Analogy for Local Variables in the “Stack”.
void function(void); // Declaration of the sub-function
void function(void) // Definition of the sub-function
{
unsigned char a; // Local variable
a=1;
}
void main() // Main function
{
function(); // Call to the sub-function
}
We see that the microcontroller executes from the main function downwards. It first encounters the call to function(), so it jumps to the definition of function() and starts executing. At this point, the local variable a begins to be allocated at a certain address in the RAM of the “stack area”, equivalent to being assigned a room in a guesthouse.
After the microcontroller finishes executing the sub-function function(), the local variable a at the RAM address allocated in the stack is reclaimed, and local variable a disappears. The reclaimed RAM address may be reassigned by the system to other local variables of called functions.
This is akin to you leaving the guesthouse; you no longer have any relationship with the room you occupied. The room you stayed in will be reassigned to other guests by the guesthouse owner.
The scope of global variables is permanent and unrestricted, while the scope of local variables is limited to the internal range of the function they are in. The global data area for global variables is a permanent private house, while the stack for local variables is a temporary guesthouse.
Summary
-
Defining a new global variable incurs the cost of a new
RAMmemory. However, defining a local variable does not incur newRAMmemory as long as the total number of local variables defined inside the function does not exceed thestackarea of the microcontroller; local variables temporarily borrow from thestackand return it after use. Thestackis a public area that can be reused and can serve several different local variables within functions. -
Each time the microcontroller enters a function, local variables are initialized and changed, while global variables are not initialized; global variables retain the last modified value.
Common Questions
Who Allocates the Global Data Area and Stack Area, and How Are They Allocated?
They are automatically allocated by the C compiler. As for how they are allocated, whether some are allocated more or less, the C compiler has a default ratio for allocation, which we generally do not need to worry about.
The Stack Area is Temporarily Borrowed; When a Sub-function is Called, Its Internal Local Variables are Temporarily Allocated to a Certain Address in the “Stack”. So Who Oversees the Allocation of the “Stack Area”?
When the microcontroller is powered on and starts running the program, the compiler is no longer in effect. The work of allocating the stack area for local variables inside functions is indeed done by the C compiler, but this occurs before the microcontroller is powered on.
The C compiler plans all the allocation work for local variables inside all functions, specifying which local variable of a function should be allocated to which address in the stack area once that function is called. The C compiler completes this allocation before it ceases to function.
When the microcontroller powers on and begins to work, although the C compiler is no longer present, the microcontroller strictly follows the instructions left by the C compiler to start working and allocating the “stack area”. Therefore, the “temporary allocation” of the stack area is not truly temporary in the strict sense.
If the Total Number of Local Variables Defined Inside Functions Exceeds the RAM Size of the “Stack” Area, What Are the Serious Consequences?
This situation is referred to as stack overflow. The program may exhibit inexplicable anomalies, and the consequences can be particularly severe.
To avoid this situation, it is generally advised not to define large arrays as local variables within functions. The number of local variables should not be too many or too large, especially avoiding the definition of large arrays as local variables.
Large arrays should be defined as global variables or as static local variables.
Some C compilers may kindly remind you when encountering a “stack overflow” situation and prevent compilation, while others may not provide any warning. Therefore, everyone should be cautious about stack overflow when writing functions in future projects.
Priority of Global and Local Variables
As mentioned earlier, the scope of global variables is permanent and unrestricted, while the scope of local variables is limited to the internal range of the function they are in.
The question arises: if a local variable and a global variable have the same name, which variable is executed within the function? This issue involves priority.
Note: When facing a local variable and a global variable with the same name, the variable executed within the function is the local variable, meaning that local variables take precedence over global variables within the function.
Let’s Look at Some Examples
First Example
unsigned char a=5; // Here, the first a is a global variable
void main() // Main function
{
unsigned char a=2; // Here, the second a is a local variable, which has the same name as the first global variable a
print(a); // Send a to the serial assistant software on the computer for observation
while(1)
{
}
}
The correct answer is 2. The local variable within the function takes precedence over the global variable.
Although the two a’s have the same name, their memory models differ. The first global variable a is allocated in the global data area, which has a unique address, while the second local variable a is allocated in the temporary stack area, residing within the main function.
Second Example
void function(void); // Function declaration
unsigned char a=5; // Here, the first a is a global variable
void function(void) // Function definition
{
unsigned char a=3; // Here, the second a is a local variable.
}
void main() // Main function
{
unsigned char a=2; // Here, the third a is also a local variable.
function(); // Call to the sub-function
print(a); // Send a to the serial assistant software on the computer for observation.
while(1)
{
}
}
The correct answer is 2. The local variable (the third local variable a) defined within the main function is the one that exists when executing the print(a) statement, as the second local variable a (inside function) no longer exists after the function call.
Third Example
void function(void); // Function declaration
unsigned char a=5; // Here, the first a is a global variable
void function(void) // Function definition
{
unsigned char a=3; // Here, the second a is a local variable
}
void main() // Main function
{
function(); // Call to the sub-function
print(a); // Send a to the serial assistant software on the computer for observation
while(1)
{
}
}
The correct answer is 5. After the function call, the local variable (the second local variable a) inside the function no longer exists. Since there is no local variable a defined within the main function, the a printed must be the first global variable a.
Conclusion
After reading this article, I believe everyone has gained a basic understanding of the stack. In embedded programming, we must always be cautious to avoid stack overflow; if there are any errors, please feel free to point them out. Until next time, goodbye.

1.Embedded Technology and Talent Cultivation in the AIoT Era
2.RT-Thread Smart Open Source Hybrid Microkernel Operating System Emerges, Replacing Linux in Smart Devices!
3.The Secrets of Huawei’s HarmonyOS
4.How Difficult is it to Design a Programming Language? The Creator of Ruby Reveals All
5.How to Effectively Ask Your Mentor Questions in the Workplace?
6.How Google Software Engineers Write Design Documents!

Disclaimer: This article is a network reprint, and the copyright belongs to the original author. If there are copyright issues, please contact us, and we will confirm the copyright based on the materials you provide and pay for the manuscript or delete the content.