How C program stored in RAM memory?
Tags: c, cpp, computerscience, programming
Published: 2019-11-01 10:47:09

<!-- wp:paragraph -->
<p>When you run any C-program, its executable image loaded into RAM of computer in an organized manner which called process address space or memory layout of C program. Here I have tried to show you the same thing in two parts. </p>
<!-- wp:list -->
<ul><li>In the 1st part i.e. "Overview", we will see segment-wise overview</li><li>In 2nd part i.e. "Example", we'll see How C program stored in RAM memory? with example.</li></ul>
<!-- /wp:list -->
<!-- /wp:paragraph -->

> /!\\\: Originally published @ [www.vishalchovatiya.com](http://www.vishalchovatiya.com).


<!-- wp:heading {"level":2} -->
<h2><strong>1st part: Overview</strong> </h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The memory layout of C program organized in the following fashion:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Text segment                </li><li>Data segment</li><li>Heap segment</li><li>Stack segment</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Note: It's not just these 4 segments, there are a lot more but these 4 are the core to understanding the working of C program at the machine level.</p>
<!-- /wp:paragraph -->

<!-- wp:enlighter/codeblock {"linenumbers":"false"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">        HIGHER  ADDRESS                                                                                                        
   +------------------------+                                                                             
   |  Unmapped or reserved  | Command-line argument &amp; Environment variables                                                                          
   |------------------------|------------------------                                                                          
   |     Stack segment      | |                                                                                                
   |           |            | | Stack frame                                                                                    
   |           v            | v                                                                                                
   |                        |                                                                                                  
   |           ^            | ^                                                                                                
   |           |            | | Dynamic memory                                                                                 
   |     Heap segment       | |                                                                                                
   |------------------------|------------------------                                                                          
   |   Uninitialized data   |                                                                                                  
   |------------------------| Data segment                                                                                     
   |    Initialized data    |                                                                                                  
   |------------------------|------------------------                                                                          
   |                        |                                                                                                  
   |      Text segment      | Executable code                                                                                  
   |                        |                                                                                                  
   +------------------------+                                                                                                  
         LOWER  ADDRESS                     </pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:heading {"level":3} -->
<h3><strong>Text segment</strong> </h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Text segment contains executable instructions of your C program, its also called code segment. </li><li>This includes all functions making up the program(<code>main()</code> too), both user-defined and system. </li><li>The text segment is sharable so that only a single copy needs to be in memory for different executing programs, such as text editors, shells, and so on. </li><li>Usually, the text segment is read-only, to prevent a program from accidentally modifying its instructions.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3><strong>Data segment</strong>&nbsp; </h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>There are two subsections of this segment</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4> <strong>Initialized data</strong></h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>It contains both static and global data that initialized with non-zero values. </li><li>This segment can be further classified into&nbsp;the read-only&nbsp;area and&nbsp;read-write&nbsp;area. </li><li>For example, The global string defined by <code>char string[ ] = "hello world"</code> and a statement like an <code>int count=1</code> outside the <code>main</code> (i.e. global) would be stored in initialized read-write area. </li><li>And a global statement like <code>const int A=3;</code> makes the variable <code>A</code> read-only and to be stored in initialized read-only area.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4> <strong>Uninitialized data (BSS segment)</strong></h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>An uninitialized data segment also called the BSS( 'Block Started by Symbol' ) segment. Which contains all global and static variables that initialized to zero or do not have explicit initialization in source code.</li><li>For example, The global variable declared as <code>int A</code> would be stored in the uninitialized data segment. A statement like static <code>int X=0</code> will also be stored in this segment cause it initialized with zero. </li><li>If you do not initialize a global variable, by default value is zero. This flushing memory content is usually done by program loader(i.e. <code>/lib/ld-linux.so.2</code>).</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3><strong>Heap segment</strong> </h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>The heap segment is an area where dynamically allocated memory (allocated by <code>malloc()</code>, <code>calloc()</code>, <code>realloc()</code> and <code>new</code> for C++) resides.</li><li>When we allocate memory through dynamic allocation techniques(in other words, run-time memory allocation), program acquire space from OS and process address space grows.</li><li>We can free dynamically allocated memory space (by using <code>free()</code> or <code>delete</code>). Freed memory goes back to the heap but doesn’t have to be returned to OS (it doesn't have to be returned at all), so unordered <code>malloc</code>/<code>free</code> eventually, cause&nbsp;heap fragmentation. You can learn more about how malloc works <a rel="noreferrer noopener" aria-label="here (opens in a new tab)" href="http://www.vishalchovatiya.com/free-malloc-work-c/" target="_blank"><span style="color:#130ace" class="color">here</span></a>.</li><li>When we use dynamic allocation to acquire memory space we must keep track of allocated memory by using its address.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3><strong>Stack segment</strong></h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>The stack segment is an area where local variables stored. By saying local variable means that all those variables which are declared in every function including <code>main()</code> in your C program. I have written a detailed article about the stack frame <a rel="noreferrer noopener" aria-label="here (opens in a new tab)" href="http://www.vishalchovatiya.com/how-c-program-stored-in-ram-memory/" target="_blank"><span style="color:#2e0dd5" class="color">here</span></a>. </li><li>When we call any function, the stack frame created and when a function returns, the stack frame destroyed/rewind including all local variables of that particular function.</li><li>A stack frame contains some data like return address, arguments passed to it, local variables, and any other information needed by the invoked function.&nbsp;&nbsp;</li><li>A stack pointer(SP) which is a special function register of CPU keeps track of stack by each push &amp; pop operation onto it, by adjusted stack pointer to next or previous address.</li><li>The direction of the stack &amp; heap growth completely depends on the compiler, ABI, OS and hardware.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":2} -->
<h2><strong>2nd part: Example </strong> </h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We have taken a simple example as above along with its memory layout.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>As we discussed in the previous part(i.e. Overview) how executable image of our program divided into the different segment and stored in memory(RAM). Now we understand those blocks by using our example code presented above.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3><strong>Loader</strong></h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li> A loader is not a segment but kind of program interpreter which reads a different segment from the binary &amp; copy it in RAM in proper fashion.</li><li>There is a binary utility command by which you can see different segments &amp; path of the loader in binary as follows: </li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"linenumbers":"false"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ readelf --segments ./a.out 

Elf file type is EXEC (Executable file)
Entry point 0x8048300
There are 9 program headers, starting at offset 52

Program Headers:
  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
  PHDR           0x000034 0x08048034 0x08048034 0x00120 0x00120 R E 0x4
  INTERP         0x000154 0x08048154 0x08048154 0x00013 0x00013 R   0x1
      [Requesting program interpreter: /lib/ld-linux.so.2]
  LOAD           0x000000 0x08048000 0x08048000 0x00608 0x00608 R E 0x1000
  LOAD           0x000f08 0x08049f08 0x08049f08 0x00118 0x00124 RW  0x1000
  DYNAMIC        0x000f14 0x08049f14 0x08049f14 0x000e8 0x000e8 RW  0x4
  NOTE           0x000168 0x08048168 0x08048168 0x00020 0x00020 R   0x4
  GNU_EH_FRAME   0x0004c4 0x080484c4 0x080484c4 0x00044 0x00044 R   0x4
  GNU_STACK      0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0x10
  GNU_RELRO      0x000f08 0x08049f08 0x08049f08 0x000f8 0x000f8 R   0x1

 Section to Segment mapping:
  Segment Sections...
   00     
   01     .interp 
   02     .interp .note.ABI-tag .hash .dynsym .dynstr .gnu.version .gnu.version_r .rel.dyn .rel.plt .init .plt .plt.got .text .fini .rodata .eh_frame_hdr .eh_frame 
   03     .init_array .fini_array .jcr .dynamic .got .got.plt .data .bss 
   04     .dynamic 
   05     .note.ABI-tag 
   06     .eh_frame_hdr 
   07     
   08     .init_array .fini_array .jcr .dynamic .got 
</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>As I have mentioned earlier, there is not only 4 segment as you can see above, but there are a lot of segments which usually depends on compiler &amp; <a rel="noreferrer noopener" aria-label="ABI (opens in a new tab)" href="https://en.wikipedia.org/wiki/Application_binary_interface" target="_blank"><span style="color:#0b3ae5" class="color">ABI</span></a>. </li><li>Above you can see, <code>.data</code>, <code>.bss</code>, <code>.text</code>, etc. segments are there. But a stack segment is not shown as its created at a run time &amp; decided by OS(precisely loader &amp; kernel).</li><li><code>INTERP</code> in the program header defines the name &amp; path of loader which going to load the current binary image into the RAM by reading these segments. Here it is <code>/lib/ld-linux.so.2</code>.</li><li>You can read more about binary file format ELF <a rel="noreferrer noopener" aria-label="here (opens in a new tab)" href="http://www.vishalchovatiya.com/understand-elf-file-format/" target="_blank"><span style="color:#2716e3" class="color">here</span></a>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3><strong>Text segment</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>When you compile C code, you get executable image(which may be in any form like <code>.bin</code>, <code>.exe</code>, <code>.hex</code>, <code>.out</code> or no extension etc). This executable image contains text segment which you see by Binutils command <code>$ objdump -d &lt;binary_name&gt;</code> and it looks like follows:</p>
<!-- /wp:paragraph -->

<!-- wp:enlighter/codeblock {"linenumbers":"false"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">.....
080483f1 &lt;main>:
 80483f1:	8d 4c 24 04          	lea    0x4(%esp),%ecx
 80483f5:	83 e4 f0             	and    $0xfffffff0,%esp
 80483f8:	ff 71 fc             	pushl  -0x4(%ecx)
.....</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:paragraph -->
<p>This is executable instructions stored in the text segment as a read-only section and shared by the processes if requires. These instructions read by CPU using program counter and stack frame created in the stack at the time of execution. Program-counter points to the address of the instruction to executed which lies in the text segment. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3> <strong>Data segment</strong> </h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4> <strong>Initialized Data segment</strong> </h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>A <code>const int x = 1;</code> stored in the read-only area. So you can not modify it accidentally.</li><li>While a string <code>char&nbsp;str[]&nbsp;=&nbsp;"Hi!";</code> &amp; <code>static&nbsp;int&nbsp;var = 0;</code>&nbsp;stored in the read-write area because we don't use a keyword like const which makes variable read-only.  </li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4> <strong>Uninitialized Data segment</strong> </h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>In our program, <code>int&nbsp;i</code> declared global goes to this area of storage because it is not initialized or initialized to zero by default.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3> <strong>Heap segment</strong> </h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>When you compile your program, memory space allocated by you i.e. all locals, static &amp; global variables fixed at compile-time.  But when code needs memory at run-time, it approach OS by calling functions like <code>malloc()</code>, <code>calloc()</code>, etc.</li><li>When OS provides dynamic memory to process it shrinks stack limit pointer which initially points to uninitialized data segment start(the technical word is "program break", read about it <a rel="noreferrer noopener" aria-label="here (opens in a new tab)" href="http://www.vishalchovatiya.com/how-do-malloc-free-work-in-c/" target="_blank"><span style="color:#2218ec" class="color">here</span></a>). </li><li>As a result heap segment grows. That's why there is no line between heap &amp; stack segment. An arrow indicates its growth of direction.</li><li>In the example code, we allocate 1-byte dynamic memory using <code>malloc()</code> function and stored its address in pointer <code>ptr</code> to keep track of that memory or to access it. </li><li>This <code>ptr</code> is a local variable of main hence it's in main's stack frame, but memory pointed by it is in a heap which I have shown by <code>*ptr</code>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3><strong>Stack segment</strong></h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>The usual starting point(not entry point which is different) of any program is <code>main()</code>, which is also a function hence, stack frame is created for it while execution. Although there are many functions called before main which I have discussed <a rel="noreferrer noopener" aria-label="here (opens in a new tab)" href="http://www.vishalchovatiya.com/before-starting-main-c-runtime/" target="_blank"><span style="color:#1411d9" class="color">here</span></a>.</li><li>As you can see in image, stack frame of <code>main()</code> is created before function <code>func()</code> as we called it nested. </li><li>As the <code>func( )</code> execution overs its local variable <code>a</code> and its stack frame will destroy(rewind is a precise word here), same goes for <code>main()</code> function also.</li><li> And this is how stack grows &amp; shrinks. </li></ul>
<!-- /wp:list -->



<!-- wp:heading {"level":3} -->
<h3><strong>FAQs</strong> </h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><strong>Q.  How do you determine the stack growth direction</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>A. </strong>Simple...! by comparing the address of two different function's local variables. </p>
<!-- /wp:paragraph -->

<!-- wp:enlighter/codeblock {"language":"c"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="c" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">int *main_ptr = NULL;
int *func_ptr = NULL;

void func() { int a; func_ptr = &a; }

int main()
{
    int a; main_ptr = &a;

    func();

    (main_ptr > func_ptr) ? printf("DOWN\n") : printf("UP\n");

    return 0;
}</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:paragraph -->
<p><strong>Q.  How do you corrupt stack deliberately</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>A.  </strong>Corrupt the SFR values stored in the stack frame.</p>
<!-- /wp:paragraph -->

<!-- wp:enlighter/codeblock {"language":"c"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="c" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">void func()
{
    int a;
    memset(&amp;a, 0, 100); // Corrupt SFR values stored in stack frame
}

int main()
{
    func();
    return 0;
}
</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:paragraph -->
<p><strong>Q.  How you can increase stack frame size</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>A. </strong>  <code>alloca()</code> is the answer. Google about it or see <a rel="noreferrer noopener" aria-label="this (opens in a new tab)" href="http://man7.org/linux/man-pages/man3/alloca.3.html" target="_blank"><span style="color:#1a0fe3" class="color">this</span></a>.</p>
<!-- /wp:paragraph -->

## Other related articles

- [How floating-point no is stored in memory?](https://dev.to/visheshpatel/how-floating-point-no-is-stored-memory-47od)
- [How C program converts into assembly?](https://dev.to/visheshpatel/how-c-program-converts-into-assembly-3m2f)
- [How do malloc & free work in C?](https://dev.to/visheshpatel/how-do-malloc-free-work-in-c-3mb6)

[Have any suggestions, query or wants to say `Hi`? Take the Pressure Off, you are just a click away.](http://www.vishalchovatiya.com/contact-2/)🖱️