How are global variables stored? - c++

AFAIK, there're 2 types of global variables, initialized and unintialized. How are they stored? Are they both stored in the executable file? I can think of initialized global variables having their initial values stored in executable file. But what needs to be stored for the uninitialized ones?
My current understanding is like this:
Executable file is organized as several sections, such as .text, .data, and .bss. Code is stored in .text section, initialized global or static data is stored in .data section, and uninitialized global or static data is stored in .bss section.
Thanks for your time to view my questions.
Update 1 - 9:56 AM 11/3/2010
I found a good reference here:
Segments in Assembly Language Source -
Building the text and data segments with .text, .data, and .bss directives
Update 2 - 10:09 AM 11/3/2010
#Michael
I define a 100 bytes of un-initialized data area in my assembly code, this 100-bytes is not stored in my executable file because it is NOT initialized.
Who will allocate the 100-byte uninitialized memory space in RAM? The program loader?
Suppose I got the following code:
int global[100];
void main(void)
{
//...
}
The global[100] is not initialzed. How will the global[100] be recoded in my executable file? And who will allocate it at what time? What if it is initialized?

Initialized variable values are stored in the .data segment of the executable. Uninitialized ones don't have to be stored. They end up in the .bss segment in RAM, but the size of the segment is zero in the executable file, just the required amount of memory is stored in the segment descriptor. The code in the .text section is accessing these via offsets into the segment. Runtime linker-loader patches these references to actual virtual addresses. See, for example, the Executable and Linkable Format, which is used on most Unix-like operating systems.

In PE files there are two sizes specified for each segment: RAWsize (size on disk) and Vsize (size in RAM).
When Vsize is larger than the RAWsize, the rest of segment in RAM is zeroed.
.bss (if present) always has RAWsize of 0, and the uninialized globlal variables are located there.
Another common approach is to make Vsize of .data larger than its RAWsize, so that the rest of the segment will hold unitialized variables.

Storage for global variables is allocated in your computer's virtual memory by the OS linker/loader at the time your program is loaded. The actual global variable storage is somewhere in the physical memory hierarchy (cache, RAM memory, SSD/HD backing storage, etc.), as mapped by the cache and VM system. It could all end up quite fragmented.
The values of initialized globals are copied from the .data segment into a portion of the allocated virtual memory. Non-initialized globals might be zeroed, or might have junk left in them, depending on the security of the particular OS under which the program is running.
The are other variations, depending on the language, compiler, language run-time, and OS.

Uninitialized variables are simply pointers at the machine level. The space for them is allocated at runtime, and the program will fill it in at some later time.
For instance, if in assembler you create a global variable global BYTE 100 that will reserve global as a pointer to a 100 byte region. The program then has access to that region for whatever it needs.
EDIT: I looked up in my assembler book and it looks like uninitialized globals are defined in the .data section just as initialized variables are. From my understanding the space is allocated in the exe (say 100 bytes as above) but will have undefined contents. On Intel machines in Windows it will be garbage; the program is responsible for initializing it. Hope this helps!

Related

Why setting a value of global array has impact on executable file?

When I set my array to {1,1}, size of the executable file increase from 10 KiB to 7 MiB. But when I set it to {}, the size doesn't change.
long long fib[1000001] = {1,1}; // 7 MiB
long long fib[1000001] = {}; // 10 KiB
I use C++20 and g++ 8.1.0.
It only happens with global variables and it doesn't matter what type of memory it uses.
If a global variable is initialized to zero, the executable does not have to contain actual storage for it. It merely needs to tell the OS's executable loader that "I need X storage of bytes for global data", and the loader will provide that. That memory will be zeroed out.
However, if a global variable is initialized to something non-zero, even partially, then its data has to come from somewhere. The simplest solution is to generate the bytes of data at compile-time and shove them into the executable. At runtime, references to the global variable point into the loaded executable's storage.
While this is platform/OS specific, it's generally how most executables and compilers work

Where are global (statically compiled) variables located?

Lets say I have the following program. Which part of memory is a allocated in? Also is the behavior same for both c and c++?
// a is allocated in the ?
int a[3] = {1, 2, 3};
int main()
{
// x is allocated in the stack
int x[3] = {4, 5, 6}
// y is allocated in the heap
int* y = malloc(sizeof(int)*3);
}
Where they are allocated is dependent on your machine architecture and your compiler and linker implementation (neither of which you have specified).
the C++ Language Standard has nothing to say on the subject.
In static storage, to use standard speak. It doesn't really say much of anything about how static storage should be implemented, other than that it should endure for the whole time of the program and that it should be implicitly zero initialized if no nonzero initializer is given.
Practically in ELF binaries, these variables are all concatenated into sections, which get, at load time, mapped onto segments, which are basically memory blocks with certain memory protection bits on or off. If the global variable is writable and initialized with a nonzero value, it'll go into an ELF section designated as .data. zero-initialized variables will go into .bss (not part of the binary image so as to save space) and const static variables will go into .rodata, which will get mapped read-only, to facilitate write protection.
Your compiler's binutils (such as nm or objdump) can allow you to peek into the (implementation-dependent) details.
This is an implementation detail, the same is true for stack and heap. The language C doesn't have such concepts. If your implementation uses a heap, it probably also uses segments in a binary format provided by the OS. In that case, static variables are placed in a data or bss segment, so they are either part of the program itself (data) or allocated by the OS when loading the program (bss).
A somewhat common approach is to place default-initialized variables in bss because this way, they don't increase the size of the executable file. For constant data, there's often a rodata segment available, many C compilers put string literals there.
But bottom line is: you shouldn't care as C doesn't specify this and there are platforms that don't provide segments, or a heap, ...

Where machine instructions of a program stored during runtime?

So far as I know, whenever we run any program, the machine instructions of the program is loaded in RAM. Again, there are two regions of memory: stack and heap.
My question is: Which region of memory the machine instruction stored in? stack or heap?
I learnt that the following program gives a runtime error though there is no variable declared inside the function. The reason behind this is the overflow of stack. Then should I assume that the machines instructions of the function is stored in stack?
int func()
{
return func();
}
Neither, as it is not dynamically allocated the way stack and heap are.
The executable loader loads the executable (.text) and any static data it contains, like the initial values of global variables (.data / .rodata), into an unused RAM area. It then sets up any zero-initialized memory the executable asked for (.bss).
Only then is the stack set up for main(). Stack memory is allocated on the stack if you enter another function, holding the return address, function arguments, and any locally declared variables as well as any memory allocated via alloca().[1] Memory is released when you return from the function.
Heap memory is allocated by malloc(), calloc(), or realloc(). It gets released when you free() or realloc() it.
The RAM used for the executable and its static data does not get released until the process terminates.
Thus, stack and heap are, basically, under control of the application. The memory of the executable itself is under control of the executable loader / the operating system. In appropriately equipped operating systems, you don't even have write access to that memory.
Regarding your edited question, no. (Bad style, editing a question to give it a completely new angle.)
The executable code remains where it was loaded. Calling a function does not place machine instructions on the stack. The only thing your func() (a function taking no arguments) places on the stack is the return address, a pointer that indicates where execution should continue once the current function returns.
Since none of the calls ever returns, your program keeps adding return addresses on the stack, until that cannot hold any more. This has nothing to do with machine code instructions at all.
[1]: Note that none of this is actually part and parcel of the C language standard, but implementation-defined, and may differ -- I presented a simplified version of affairs. For example, function parameters might be passed in CPU registers instead of on the stack.
Neither one nor the other.
The image of your program contains the code and the static data (f.e. all you string constants, static arrays and structures, and so on). They will be loaded into different segments of the RAM.
Stack and heap are dynamic structures to store data, they will be created at the start of your program. Stack is hardware supported solutions, while heap is a standard library supported solution.
So, your code will be located in the code segment, your static data and heap will be located in the data segment, and the stack will be located in the stack segment.
the machine instructions of the program is loaded in RAM
Correct for hosted, "PC-like" systems. On embedded systems, code is most often executed directly from flash memory
Again, there is two regions of memory: stack and heap.
No, that's some over-simplification that way too many, way too bad programming teachers teach.
There are lots of other regions too: .data and .bss where all variables with static storage go, .rodata where constants go, etc etc.
The segment where the program code is stored is usually called .text.
Again, there is two regions of memory: stack and heap.
It's not that simple. Normally on mainstream operating system there's more stuff going on:
there is one stack per running thread;
there are as many heaps as you decide to allocate (actually, as far as the memory manager is concerned you ask some memory pages to "enabled" in your virtual address space, the "heap" thing derives from the fact that normally one uses some kind of heap manager code to efficiently distribute these memory portions between allocations);
there can be memory mapped files and shared memory;
most importantly, the executable file (and the dynamic libraries) are mapped in the memory of the process, normally with the code zone (the so called "text" segment) mapped in read-only mode, and other zones (typically pertaining to initialized global and static variables and stuff fixed by the loader) in copy-on-write.
So, the code is stored in the relevant section of the executable, which is mapped in memory.
They are usually on a section called .text.
On Linux you can list the sections of an ELF object or executable with size command from core-utils, for example on a tst ELF executable:
$ size -Ax tst | grep "^\.text"
.text 0x1e8 0x4003b0
$
There are multiple memory segments in addition to the stack and heap. Here's an example of how a program may be laid out in memory:
+------------------------+
high address | Command line arguments |
| and environment vars |
+------------------------+
| stack |
| - - - - - - - - - - - |
| | |
| V |
| |
| ^ |
| | |
| - - - - - - - - - - - |
| heap |
+------------------------+
| global and read- |
| only data |
+------------------------+
| program text |
low address | (machine code) |
+------------------------+
Details will vary from platform to platform, but this layout is pretty common for x86-based systems. The machine code occupies its own memory segment (labeled .text in ELF format), global read-only data will be stored in another segment (.rdata or .rodata), uninitialized globals in yet another segment (.bss), etc. Some segments are read-only, some are writable.
Neither heap nor stack.
Usually, executable instructions are present in Code segment.
Quoting the wikipedia article
In computing, a code segment, also known as a text segment or simply as text, is a portion of an object file or the corresponding section of the program's virtual address space that contains executable instructions.
and
when the loader places a program into memory so that it may be executed, various memory regions are allocated (in particular, as pages)
At runtime, the code segment of an object file is loaded into a corresponding code segment in memory. In particular, it has nothing to do with stack or heap.
EDIT:
In your code snippet above, what you're experiencing is called infinite recursion.
Even if you function does not need any space in stack for local variable, it still needs to push the return address of the outer function before calling the inner function, thus claiming the stack space, only never to return [pop the addresses out of stack] [like at a point of no return], thereby running out of stack space, causing stack overflow.

What does "Memory allocated at compile time" really mean?

In programming languages like C and C++, people often refer to static and dynamic memory allocation. I understand the concept but the phrase "All memory was allocated (reserved) during compile time" always confuses me.
Compilation, as I understand it, converts high level C/C++ code to machine language and outputs an executable file. How is memory "allocated" in a compiled file ? Isn't memory always allocated in the RAM with all the virtual memory management stuff ?
Isn't memory allocation by definition a runtime concept ?
If I make a 1KB statically allocated variable in my C/C++ code, will that increase the size of the executable by the same amount ?
This is one of the pages where the phrase is used under the heading "Static allocation".
Back To Basics: Memory allocation, a walk down the history
Memory allocated at compile-time means the compiler resolves at compile-time where certain things will be allocated inside the process memory map.
For example, consider a global array:
int array[100];
The compiler knows at compile-time the size of the array and the size of an int, so it knows the entire size of the array at compile-time. Also a global variable has static storage duration by default: it is allocated in the static memory area of the process memory space (.data/.bss section). Given that information, the compiler decides during compilation in what address of that static memory area the array will be.
Of course that memory addresses are virtual addresses. The program assumes that it has its own entire memory space (From 0x00000000 to 0xFFFFFFFF for example). That's why the compiler could do assumptions like "Okay, the array will be at address 0x00A33211". At runtime that addresses are translated to real/hardware addresses by the MMU and OS.
Value initialized static storage things are a bit different. For example:
int array[] = { 1 , 2 , 3 , 4 };
In our first example, the compiler only decided where the array will be allocated, storing that information in the executable.
In the case of value-initialized things, the compiler also injects the initial value of the array into the executable, and adds code which tells the program loader that after the array allocation at program start, the array should be filled with these values.
Here are two examples of the assembly generated by the compiler (GCC4.8.1 with x86 target):
C++ code:
int a[4];
int b[] = { 1 , 2 , 3 , 4 };
int main()
{}
Output assembly:
a:
.zero 16
b:
.long 1
.long 2
.long 3
.long 4
main:
pushq %rbp
movq %rsp, %rbp
movl $0, %eax
popq %rbp
ret
As you can see, the values are directly injected into the assembly. In the array a, the compiler generates a zero initialization of 16 bytes, because the Standard says that static stored things should be initialized to zero by default:
8.5.9 (Initializers) [Note]:
Every object of static storage duration is zero-initialized at
program startup before any other initial- ization takes place. In some
cases, additional initialization is done later.
I always suggest people to disassembly their code to see what the compiler really does with the C++ code. This applies from storage classes/duration (like this question) to advanced compiler optimizations. You could instruct your compiler to generate the assembly, but there are wonderful tools to do this on the Internet in a friendly manner. My favourite is GCC Explorer.
Memory allocated at compile time simply means there will be no further allocation at run time -- no calls to malloc, new, or other dynamic allocation methods. You'll have a fixed amount of memory usage even if you don't need all of that memory all of the time.
Isn't memory allocation by definition a runtime concept?
The memory is not in use prior to run time, but immediately prior to execution starting its allocation is handled by the system.
If I make a 1KB statically allocated variable in my C/C++ code, will that increase the size of the executable by the same amount?
Simply declaring the static will not increase the size of your executable more than a few bytes. Declaring it with an initial value that is non-zero will (in order to hold that initial value). Rather, the linker simply adds this 1KB amount to the memory requirement that the system's loader creates for you immediately prior to execution.
Memory allocated in compile time means that when you load the program, some part of the memory will be immediately allocated and the size and (relative) position of this allocation is determined at compile time.
char a[32];
char b;
char c;
Those 3 variables are "allocated at compile time", it means that the compiler calculates their size (which is fixed) at compile time. The variable a will be an offset in memory, let's say, pointing to address 0, b will point at address 33 and c at 34 (supposing no alignment optimization). So, allocating 1Kb of static data will not increase the size of your code, since it will just change an offset inside it. The actual space will be allocated at load time.
Real memory allocation always happens in run time, because the kernel needs to keep track of it and to update its internal data structures (how much memory is allocated for each process, pages and so on). The difference is that the compiler already knows the size of each data you are going to use and this is allocated as soon as your program is executed.
Remember also that we are talking about relative addresses. The real address where the variable will be located will be different. At load time the kernel will reserve some memory for the process, lets say at address x, and all the hard coded addresses contained in the executable file will be incremented by x bytes, so that variable a in the example will be at address x, b at address x+33 and so on.
Adding variables on the stack that take up N bytes doesn't (necessarily) increase the bin's size by N bytes. It will, in fact, add but a few bytes most of the time.
Let's start off with an example of how adding a 1000 chars to your code will increase the bin's size in a linear fashion.
If the 1k is a string, of a thousand chars, which is declared like so
const char *c_string = "Here goes a thousand chars...999";//implicit \0 at end
and you then were to vim your_compiled_bin, you'd actually be able to see that string in the bin somewhere. In that case, yes: the executable will be 1 k bigger, because it contains the string in full.
If, however you allocate an array of ints, chars or longs on the stack and assign it in a loop, something along these lines
int big_arr[1000];
for (int i=0;i<1000;++i) big_arr[i] = some_computation_func(i);
then, no: it won't increase the bin... by 1000*sizeof(int)
Allocation at compile time means what you've now come to understand it means (based on your comments): the compiled bin contains information the system requires to know how much memory what function/block will need when it gets executed, along with information on the stack size your application requires. That's what the system will allocate when it executes your bin, and your program becomes a process (well, the executing of your bin is the process that... well, you get what I'm saying).
Of course, I'm not painting the full picture here: The bin contains information about how big a stack the bin will actually be needing. Based on this information (among other things), the system will reserve a chunk of memory, called the stack, that the program gets sort of free reign over. Stack memory still is allocated by the system, when the process (the result of your bin being executed) is initiated. The process then manages the stack memory for you. When a function or loop (any type of block) is invoked/gets executed, the variables local to that block are pushed to the stack, and they are removed (the stack memory is "freed" so to speak) to be used by other functions/blocks. So declaring int some_array[100] will only add a few bytes of additional information to the bin, that tells the system that function X will be requiring 100*sizeof(int) + some book-keeping space extra.
On many platforms, all of the global or static allocations within each module will be consolidated by the compiler into three or fewer consolidated allocations (one for uninitialized data (often called "bss"), one for initialized writable data (often called "data"), and one for constant data ("const")), and all of the global or static allocations of each type within a program will be consolidated by the linker into one global for each type. For example, assuming int is four bytes, a module has the following as its only static allocations:
int a;
const int b[6] = {1,2,3,4,5,6};
char c[200];
const int d = 23;
int e[4] = {1,2,3,4};
int f;
it would tell the linker that it needed 208 bytes for bss, 16 bytes for "data", and 28 bytes for "const". Further, any reference to a variable would be replaced with an area selector and offset, so a, b, c, d, and e, would be replaced by bss+0, const+0, bss+4, const+24, data+0, or bss+204, respectively.
When a program is linked, all of the bss areas from all the modules are be concatenated together; likewise the data and const areas. For each module, the address of any bss-relative variables will be increased by the size of all preceding modules' bss areas (again, likewise with data and const). Thus, when the linker is done, any program will have one bss allocation, one data allocation, and one const allocation.
When a program is loaded, one of four things will generally happen depending upon the platform:
The executable will indicate how many bytes it needs for each kind of data and--for the initialized data area, where the initial contents may be found. It will also include a list of all the instructions which use a bss-, data-, or const- relative address. The operating system or loader will allocate the appropriate amount of space for each area and then add the starting address of that area to each instruction which needs it.
The operating system will allocate a chunk of memory to hold all three kinds of data, and give the application a pointer to that chunk of memory. Any code which uses static or global data will dereference it relative to that pointer (in many cases, the pointer will be stored in a register for the lifetime of an application).
The operating system will initially not allocate any memory to the application, except for what holds its binary code, but the first thing the application does will be to request a suitable allocation from the operating system, which it will forevermore keep in a register.
The operating system will initially not allocate space for the application, but the application will request a suitable allocation on startup (as above). The application will include a list of instructions with addresses that need to be updated to reflect where memory was allocated (as with the first style), but rather than having the application patched by the OS loader, the application will include enough code to patch itself.
All four approaches have advantages and disadvantages. In every case, however, the compiler will consolidate an arbitrary number of static variables into a fixed small number of memory requests, and the linker will consolidate all of those into a small number of consolidated allocations. Even though an application will have to receive a chunk of memory from the operating system or loader, it is the compiler and linker which are responsible for allocating individual pieces out of that big chunk to all the individual variables that need it.
The core of your question is this: "How is memory "allocated" in a compiled file? Isn't memory always allocated in the RAM with all the virtual memory management stuff? Isn't memory allocation by definition a runtime concept?"
I think the problem is that there are two different concepts involved in memory allocation. At its basic, memory allocation is the process by which we say "this item of data is stored in this specific chunk of memory". In a modern computer system, this involves a two step process:
Some system is used to decide the virtual address at which the item will be stored
The virtual address is mapped to a physical address
The latter process is purely run time, but the former can be done at compile time, if the data have a known size and a fixed number of them is required. Here's basically how it works:
The compiler sees a source file containing a line that looks a bit like this:
int c;
It produces output for the assembler that instructs it to reserve memory for the variable 'c'. This might look like this:
global _c
section .bss
_c: resb 4
When the assembler runs, it keeps a counter that tracks offsets of each item from the start of a memory 'segment' (or 'section'). This is like the parts of a very large 'struct' that contains everything in the entire file it doesn't have any actual memory allocated to it at this time, and could be anywhere. It notes in a table that _c has a particular offset (say 510 bytes from the start of the segment) and then increments its counter by 4, so the next such variable will be at (e.g.) 514 bytes. For any code that needs the address of _c, it just puts 510 in the output file, and adds a note that the output needs the address of the segment that contains _c adding to it later.
The linker takes all of the assembler's output files, and examines them. It determines an address for each segment so that they won't overlap, and adds the offsets necessary so that instructions still refer to the correct data items. In the case of uninitialized memory like that occupied by c (the assembler was told that the memory would be uninitialized by the fact that the compiler put it in the '.bss' segment, which is a name reserved for uninitialized memory), it includes a header field in its output that tells the operating system how much needs to be reserved. It may be relocated (and usually is) but is usually designed to be loaded more efficiently at one particular memory address, and the OS will try to load it at this address. At this point, we have a pretty good idea what the virtual address is that will be used by c.
The physical address will not actually be determined until the program is running. However, from the programmer's perspective the physical address is actually irrelevant—we'll never even find out what it is, because the OS doesn't usually bother telling anyone, it can change frequently (even while the program is running), and a main purpose of the OS is to abstract this away anyway.
An executable describes what space to allocate for static variables. This allocation is done by the system, when you run the executable. So your 1kB static variable won't increase the size of the executable with 1kB:
static char[1024];
Unless of course you specify an initializer:
static char[1024] = { 1, 2, 3, 4, ... };
So, in addition to 'machine language' (i.e. CPU instructions), an executable contains a description of the required memory layout.
Memory can be allocated in many ways:
in application heap (whole heap is allocated for your app by OS when the program starts)
in operating system heap (so you can grab more and more)
in garbage collector controlled heap (same as both above)
on stack (so you can get a stack overflow)
reserved in code/data segment of your binary (executable)
in remote place (file, network - and you receive a handle not a pointer to that memory)
Now your question is what is "memory allocated at compile time". Definitely it is just an incorrectly phrased saying, which is supposed to refer to either binary segment allocation or stack allocation, or in some cases even to a heap allocation, but in that case the allocation is hidden from programmer eyes by invisible constructor call. Or probably the person who said that just wanted to say that memory is not allocated on heap, but did not know about stack or segment allocations.(Or did not want to go into that kind of detail).
But in most cases person just wants to say that the amount of memory being allocated is known at compile time.
The binary size will only change when the memory is reserved in the code or data segment of your app.
You are right. Memory is actually allocated (paged) at load time, i.e. when the executable file is brought into (virtual) memory. Memory can also be initialized on that moment. The compiler just creates a memory map. [By the way, stack and heap spaces are also allocated at load time !]
I think you need to step back a bit. Memory allocated at compile time.... What can that mean? Can it mean that memory on chips that have not yet been manufactured, for computers that have not yet been designed, is somehow being reserved? No. No, time travel, no compilers that can manipulate the universe.
So, it must mean that the compiler generates instructions to allocate that memory somehow at runtime. But if you look at it in from the right angle, the compiler generates all instructions, so what can be the difference. The difference is that the compiler decides, and at runtime, your code can not change or modify its decisions. If it decided it needed 50 bytes at compile time, at runtime, you can't make it decide to allocate 60 -- that decision has already been made.
If you learn assembly programming, you will see that you have to carve out segments for the data, the stack, and code, etc. The data segment is where your strings and numbers live. The code segment is where your code lives. These segments are built into the executable program. Of course the stack size is important as well... you wouldn't want a stack overflow!
So if your data segment is 500 bytes, your program has a 500 byte area. If you change the data segment to 1500 bytes, the size of the program will be 1000 bytes larger. The data is assembled into the actual program.
This is what is going on when you compile higher level languages. The actual data area is allocated when it is compiled into an executable program, increasing the size of the program. The program can request memory on the fly, as well, and this is dynamic memory. You can request memory from the RAM and the CPU will give it to you to use, you can let go of it, and your garbage collector will release it back to the CPU. It can even be swapped to a hard disk, if necessary, by a good memory manager. These features are what high level languages provide you.
I would like to explain these concepts with the help of few diagrams.
This is true that memory cannot be allocated at compile time, for sure.
But, then what happens in fact at compile time.
Here comes the explanation.
Say, for example a program has four variables x,y,z and k.
Now, at compile time it simply makes a memory map, where the location of these variables with respect to each other is ascertained.
This diagram will illustrate it better.
Now imagine, no program is running in memory.
This I show by a big empty rectangle.
Next, the first instance of this program is executed.
You can visualize it as follows.
This is the time when actually memory is allocated.
When second instance of this program is running, the memory would look like as follows.
And the third ..
So on and so forth.
I hope this visualization explains this concept well.
There is very nice explanation given in the accepted answer. Just in case i will post the link which i have found useful.
https://www.tenouk.com/ModuleW.html
One among the many thing what a compiler does is that create and maintain a SYMTAB(Symbol Table under the section.symtab). This will be purely created and maintained by compilers using any Data Structure(List, Trees...etc) and not for the developers eyes. Any access request made by the developers this is where it will hit first.
Now about the Symbol Table,
We only need to know about the two columns Symbol Name and the Offset.
Symbol Name column will have the variable names and the offset column will have the offset value.
Lets see this with an example:
int a , b , c ;
Now we all know that the register Stack_Pointer(sp) points to the Top of the Stack Memory. Let that be sp = 1000.
Now the Symbol Name column will have three values in it a then b and then c. Reminding you all that variable a will be at the top of the stack memory.
So a's equivalent offset value will be 0.
(Compile Time Offset_Value)
Then b and its equivalent offset value will be 1. (Compile Time Offset_Value)
Then c and its equivalent offset value will be 2. (Compile Time Offset_Value)
Now calculating a's Physical address (or) Runtime Memory Address = (sp + offset_value of a)
= (1000 + 0) = 1000
Now calculating b's Physical address (or) Runtime Memory Address = (sp - offset_value of b)
= (1000 - 1) = 996
Now calculating c's Physical address (or) Runtime Memory Address = (sp - offset_value of c)
= (1000 - 2) = 992
Therefore at the time of the compilation we will only be having the offset values and only during the runtime the actual physical addresses are calculated.
Note:
Stack_Pointer value will be assigned only after the program is loaded. Pointer Arithmetic happens between the Stack_Pointer register and the variables offset to calculate the variables Physical Address.
"POINTERS AND POINTER ARITHMETIC, WAY OF THE PROGRAMMING WORLD"
Share what I learned about this question.
You can understand this issue in two steps:
First, the compilation step: the compiler generates the binary. In Linux system, binary is a file in ELF (Executable and Linkable Format) format. ELF file contains several sections, including .bss and .data
.data
Initialized data, with read/write access rights
.bss
Uninitialized data, with read/write access rights (=WA)
.data and .bss just map to the segments of process's memory layout, which contains static variables.
second, the loading step. When the binary file get executed, the ELF file will be loaded into process's memory. The loader can find static variables' information from ELF file.
Simply speaking, the compiler and the loader follow the same standard to communicate with each other, and the standard is ELF format.

data section in C++

I have a question to clarify my confusion about the memory organization in computer in C++.
In C++, different data is put in different location. My understanding is like this.
1) data segment section, where global and static data are located;
2) heap section, the objects created by new
3) stack section, the local variable
4) text section, the code itself.
Is that right? Is there anything I missed or did wrong?
Thanks!
I wrote an article called "C++ Internals :: Memory Layout" which will clarify this for you.
Short excerpt from the article:
.text segment
It's a Read-Only, fixed-size segment.
The text segment, a.k.a. code segment, contains executable instructions provided by the compiler and assembler.
.data segment
It's a Read-Write, fixed-size segment.
The data segment, a.k.a. initialized data segment, contains initialized:
global variables (including global static variables)
static local variables.
The segment's size depends on the size of the values in the source code, the values can be altered at run-time.
.rdata/.rodata segment
It's a Read-Only segment
The segments contains static unnamed data (like string constants)
.bss segment
It's a Read-Write and adjacent to the .data segment.
BSS segment, a.k.a. uninitialized data segment, contains statically-allocated (global and static) variables represented solely by zero-valued bits on program start. BSS stands for Block Started by Symbol, a pseudo-operation that existed in a very old assembler developed for the IBM.
heap & stack
You are quite right about those. Anyway, if you want to check some examples and get a closer look, please, refer to mentioned article.
There are typically at least two data sections. One with initialized globals, another without (BSS). A stack section isn't typically emitted in the binary.
Of course, these kind of very implementation specific questions are kinda useless if you don't specify the implementation.