Memory Regions - Static
#memory | #lowlevel | #cacheThink of static/global memory like a public notice board in an office. Unlike local (stack) variables, the information stays there throughout the program's execution. Static memory is used for storing global variables, static variables, and constant data. These variables are allocated when the program starts and remain in memory until the program ends.
Key Characteristics
- Exists for the entire program duration;
- Used for global variables, static variables, and constant data;
- This memory is often segmented further into specific sections (e.g., for data and constants);
Limitations
- Not as fast as cache or registers, but faster than heap access;
- Can possibly keep unused data in memory, allowing for more risks of memory leak;
- If multiple functions modify the same global variable, it can lead to unexpected bugs;
Example
#include <stdio.h>
int globalVar = 10; // Stored in static/global memory
void modifyGlobalFromAnotherProgramsScope() {
globalVar += 5;
}
int main() {
printf("Global variable before: %d\n", globalVar);
modifyGlobalFromAnotherProgramsScope();
printf("Global variable after: %d\n", globalVar);
return 0;
}