This post is a serie of publications that I will publish about different technical topics. This is and will not be a high and complex guide about what specific topics, but could be used as a start point to learn terms and test new knowloadge. It’s time to start, consider the following c code and guess the output:
Well, if you compile and run the program, you will see the output is 20. But what happend if we slightly modify the above code. Let’s add a new function called bar.
Run the program again, you will find out that the ouput of the program has changed. So what happened, how come the value is changed. The principle behind these two c code is the idea of local variable and the memory of variable. Let’s try to understand those topics:
- Variable Memory
- Stack Frame
- Local Variable
- Global Variable
- Static Variable
NOTE: The above c code is only for demo purpose, no one will really write this kind of code (Return a local variable address) in reality. A more complex situation may be passing a structure pointer to a function and assign some address to the fields of the structure. In this case, the idea is the same, value of dereferencing each address may be unpredictable.
Memory of Variable:
A process virtual address space can be seperated into several sections, such as code section, data section, stack, heap and etc. To get some information about a process virtual address space in linux, simply type cat /proc/$pid/maps
In C, the memory of an variable may within in three section which are 1. data section 2. stack 3. heap
The address of variable that is in data section are determine by compiler. That is the address is determine in compile time. On the other hand, the address of variable in stack or heap is determine in run time. As a result, there is no way to use some static analyze tools to find out the address of the variable in stack/heap. Let’s took the following code as an example.
Source Code Output:
As you can see from the above output, heap_var address is 0x1214010 which is in the heap
section(0x1214000 - 0x01235000). The
0x4478f7e4 which is in the stack
section(0x44771000 - 0x44792000). And finally, the
0x600b40 which is in the data section.
In the previous section, we have a breif understanding about the address of variable. We now know that the variable in data section is determine by compiler, how about the variable in stack. The address of variable in stack can only determine
Local Variable and Global Variable and Static Variable:
We have heard these phrases for many times, but do we really understand the idea of all of them.