Where C Variables are Stored in Memory
Memory sections
- stack - the portion of memory that stores variables that were declared inside functions (i.e. stores local variables and constants)
- local variables are freed when the function returns (these variables cannot be accessed once the function ends)
- Stack memory grows downward
- heap - the portion of memory that stores things that were created by malloc()
- Data on the heap persists across functions (unlike the local variables of stack memory)
- Heap memory grows upward
- static - the portion of memory that stores "pre-allocated" variables including static and global variables (variables declared outside functions), constants, and string literals
- Two sections of static memory:
- read-only (stores variables that can only be read and not modified)
- read-write (stores variables that can be both read and written to (modified))
- Static memory does not grow or shrink
- code (text) - the portion of memory that stores the executable instructions and constants
- Code memory is loaded when the program starts
- Code memory does not grow or shrink
Where data of a program can be stored in memory
- Static variables: Static memory
- Local variables: Stack memory
- Global variables: Static memory
- Constants: Code, Static, and Stack memory
- Constants in Code: #define CONSTANT (~value~)
- Constants in Static memory: declare const (~variable~) = (~value~); outside of all functions
- Constants in Stack memory: declare const (~variable~) = (~variable~); inside a function
- Machine instructions: Code memory
- Result of malloc: Heap memory
- String literals/constants: Static memory
Where C strings are stored in memory
- Pointer initialization of a string will be stored in static memory (a.k.a. string literals)
- Example: char * s = "Hello"
- "Hello" is a string stored in static memory
- Pointer s points to that string stored in static memory
- The section of memory that variable s is stored in depends on where/how it was declared (e.g. if s was declared in a function, s is in stack memory)
- A string literal is immutable (the string is stored in a read-only block in static memory)
- Array initialization of the string will be stored in stack memory
- Example: char s[6] = "Hello"
- Array s is put onto the stack, and the characters "h" "e" "l" "l" "o" are inserted into the location on the stack where the array is
- Both s and s[0] are in stack memory
Comments
Post a Comment