As far as I know, global and static variables are stored in heap memory, while local variables are on stack memory. I think this is the case when we speak about a binary file (like PE) that is located in memory. If this is correct, I am wondering: Are local and global variables stored plainly in a disk image (binary in Disk), can we see them directly by inspecting the disk image?
First, local variables needn't be stored on the stack. Modern compilers will first try to use CPU registers to store local variables.
Next, heap and stack are terms that relate to virtual memory. Virtual memory starts to exist when the operating system creates the process. It does not exist when the file is on disk only. Therefore, you can never see a variable on disk.
Now, @user2073973 left a comment that the variables are stored in the
.data section. This is typically true, but
- a compiler does not need to generate a
.datasection, if he can avoid it by other means.
- without symbols, the
.datasection is just data. You don't know which portion will make up a variable.
AB12CD34EFcould be 5
bytes or 1
Data storage on modern OSes and their appropriate file formats is far more complex than that.
There are multiple locations to store variables, of those the more predominant are:
- The stack. This is where small-scoped variables are usually stored, often defined in the function or code block level. Those variables are relatively "cheap" to allocate but their scope is limited isn't flexible. Stack is somewhat limited in size, and allocating too many big variables may cause stack overflow crashes.
- The heap. The heap allows more control and flexibility of the scope a variable leaves in, at the cost of bugs potential (memory leaks, heap corruption) and security vulnerabilities. It is also slightly more "expensive" to allocate performance-wise. The heap is only limited buy the address space size and available RAM, when RAM limitations are mitigated by using the page file (called swap in Linux/Mac).
- Virtual memory (directly). Quite similar to the heap, but instead of using the OS's flexible-size heap chunks allocation, allocating entire pages and managing their partition manually. This is quite similar and rarely used in common-day programs.
- pre-allocated regions. Some global-scoped variables (global and static variables are stored here, not on the heap) are often allocated inside PE regions designated for variables. These regions are often divided to an uninitialized section and an initialized section.
The last one, the pre-allocated regions, is the only type of variable storage encoded in the PE file directly and the only one there's a chance to access from the hard drive, but only initial values are readable. You cannot use that to read current variable values (because those will only be stored in memory).