The Wayback Machine - https://web.archive.org/web/20240713000938/https://www.geeksforgeeks.org/memory-layout-of-c-program/
Open In App

Memory Layout of C Programs

Last Updated : 24 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report
 

A typical memory representation of a C program consists of the following sections.

  1. Text segment  (i.e. instructions)
  2. Initialized data segment 
  3. Uninitialized data segment  (bss)
  4. Heap 
  5. Stack 

A typical memory layout of a running process

1. Text Segment: A text segment, also known as a code segment or simply as text, is one of the sections of a program in an object file or in memory, which contains executable instructions.
As a memory region, a text segment may be placed below the heap or stack in order to prevent heaps and stack overflows from overwriting it. 

Usually, the text segment is sharable so that only a single copy needs to be in memory for frequently executed programs, such as text editors, the C compiler, the shells, and so on. Also, the text segment is often read-only, to prevent a program from accidentally modifying its instructions.

2. Initialized Data Segment: Initialized data segment, usually called simply the Data Segment. A data segment is a portion of the virtual address space of a program, which contains the global variables and static variables that are initialized by the programmer.
Note that, the data segment is not read-only, since the values of the variables can be altered at run time.
This segment can be further classified into the initialized read-only area and the initialized read-write area.
For instance, the global string defined by char s[] = “hello world” in C and a C statement like int debug=1 outside the main (i.e. global) would be stored in the initialized read-write area. And a global C statement like const char* string = “hello world” makes the string literal “hello world” to be stored in the initialized read-only area and the character pointer variable string in the initialized read-write area.
Ex: static int i = 10 will be stored in the data segment and global int i = 10 will also be stored in data segment

3. Uninitialized Data Segment: Uninitialized data segment often called the “bss” segment, named after an ancient assembler operator that stood for “block started by symbol.” Data in this segment is initialized by the kernel to arithmetic 0 before the program starts executing uninitialized data starts at the end of the data segment and contains all global variables and static variables that are initialized to zero or do not have explicit initialization in source code.
For instance, a variable declared static int i; would be contained in the BSS segment. 
For instance, a global variable declared int j; would be contained in the BSS segment.

4. Stack: The stack area traditionally adjoined the heap area and grew in the opposite direction; when the stack pointer met the heap pointer, free memory was exhausted. (With modern large address spaces and virtual memory techniques they may be placed almost anywhere, but they still typically grow in opposite directions.)
The stack area contains the program stack, a LIFO structure, typically located in the higher parts of memory. On the standard PC x86 computer architecture, it grows toward address zero; on some other architectures, it grows in the opposite direction. A “stack pointer” register tracks the top of the stack; it is adjusted each time a value is “pushed” onto the stack. The set of values pushed for one function call is termed a “stack frame”; A stack frame consists at minimum of a return address.
Stack, where automatic variables are stored, along with information that is saved each time a function is called. Each time a function is called, the address of where to return to and certain information about the caller’s environment, such as some of the machine registers, are saved on the stack. The newly called function then allocates room on the stack for its automatic variables. This is how recursive functions in C can work. Each time a recursive function calls itself, a new stack frame is used, so one set of variables doesn’t interfere with the variables from another instance of the function.

5. Heap: Heap is the segment where dynamic memory allocation usually takes place.
The heap area begins at the end of the BSS segment and grows to larger addresses from there. The Heap area is managed by malloc, realloc, and free, which may use the brk and sbrk system calls to adjust its size (note that the use of brk/sbrk and a single “heap area” is not required to fulfill the contract of malloc/realloc/free; they may also be implemented using mmap to reserve potentially non-contiguous regions of virtual memory into the process’ virtual address space). The Heap area is shared by all shared libraries and dynamically loaded modules in a process.

Examples: 

The size(1) command reports the sizes (in bytes) of the text, data, and bss segments. ( for more details please refer man page of size(1) )

1. Check the following simple C program 

C




#include <stdio.h>
 
int main(void)
{
    return 0;
}


[narendra@CentOS]$ gcc memory-layout.c -o memory-layout
[narendra@CentOS]$ size memory-layout
text       data        bss        dec        hex    filename
960        248          8       1216        4c0    memory-layout

2. Let us add one global variable in the program, now check the size of bss (highlighted in red color).

C




#include <stdio.h>
 
int global; /* Uninitialized variable stored in bss*/
 
int main(void)
{
    return 0;
}


[narendra@CentOS]$ gcc memory-layout.c -o memory-layout
[narendra@CentOS]$ size memory-layout
text       data        bss        dec        hex    filename
 960        248         12       1220        4c4    memory-layout

3. Let us add one static variable which is also stored in bss.

C




#include <stdio.h>
 
int global; /* Uninitialized variable stored in bss*/
 
int main(void)
{
    static int i; /* Uninitialized static variable stored in bss */
    return 0;
}


[narendra@CentOS]$ gcc memory-layout.c -o memory-layout
[narendra@CentOS]$ size memory-layout
text       data        bss        dec        hex    filename
 960        248         16       1224        4c8    memory-layout

4. Let us initialize the static variable which will then be stored in the Data Segment (DS)

C




#include <stdio.h>
 
int global; /* Uninitialized variable stored in bss*/
 
int main(void)
{
    static int i = 100; /* Initialized static variable stored in DS*/
    return 0;
}


[narendra@CentOS]$ gcc memory-layout.c -o memory-layout
[narendra@CentOS]$ size memory-layout
text       data        bss        dec        hex    filename
960         252         12       1224        4c8    memory-layout

5. Let us initialize the global variable which will then be stored in the Data Segment (DS)

C




#include <stdio.h>
 
int global = 10; /* initialized global variable stored in DS*/
 
int main(void)
{
    static int i = 100; /* Initialized static variable stored in DS*/
    return 0;
}


[narendra@CentOS]$ gcc memory-layout.c -o memory-layout
[narendra@CentOS]$ size memory-layout
text       data        bss        dec        hex    filename
960         256          8       1224        4c8    memory-layout

This article is compiled by Narendra Kangralkar.



Previous Article
Next Article

Similar Reads

Common Memory/Pointer Related bug in C Programs
Dereferencing an unknown memory location : C programmers mostly use scanf() function to take input, but sometimes a small mistake can bring a bug or even crash whole program. The syntax for scanf() is scanf("%d", &amp;a);. It might be possible to miss a &amp; and write &amp;a as a so now scanf("%d", a); is dereferencing to an unknown location. Now
6 min read
Output of C programs | Set 63
Prerequisite : Structure padding, integer promotion and sequence points. Q1. Consider the following code: C/C++ Code #include&lt;stdio.h&gt; struct geeks{ int i; char c; } obj; int main() { printf(&quot;%ld&quot;, sizeof(obj)); } What would be the output of the above code? A. 4 B. 5 C. 8 D. Can't be determined Output: Can't be determined Explanatio
4 min read
8085 programs to find 2's complement with carry | Set 2
Problem-1: Find 2's complement of an 8 bit number stored at address 2050. Result is stored at address 3050 and 3051. Starting address of program is taken as 2000. Example - Algorithm - We are taking complement of the number using CMA instruction.Then adding 01 to the result.The carry generated while adding 01 is stored at 3051. Program - Memory Add
3 min read
Facts and Question related to Style of writing programs in C/C++
Here are some questions related to Style of writing C programs: Question-1: Why i++ executes faster than i + 1 ? Answer-1: The expression i++ requires a single machine instruction such as INR to carry out the increment operation whereas, i + 1 requires more instructions to carry out this operation. Question-2: Is writing if(! strcmp(s1, s2) ) a goo
2 min read
Programs to print Interesting Patterns
Program to print the following pattern: Examples : Input : 5 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This program is divided into four parts. C/C++ Code // C++ program to print // the given pattern #include&lt;iostream&gt; using namespace std; void pattern(int n
15+ min read
Output of C programs | Set 30 (Switch Case)
Prerequisite - Switch Case in C/C++ Interesting Problems of Switch statement in C/C++ Program 1 #include &lt;stdio.h&gt; int main() { int num = 2; switch (num + 2) { case 1: printf(&quot;Case 1: &quot;); case 2: printf(&quot;Case 2: &quot;); case 3: printf(&quot;Case 3: &quot;); default: printf(&quot;Default: &quot;); } return 0; } Output: Default:
2 min read
C/C++ Tricky Programs
We may come across various tricky programs in our day-to-day life. Maybe in technical interviews, coding tests, or C/C++ classrooms. Here is a list of such programs:- Print text within double quotes (" "). This may seem easy, but beginners may get puzzled while printing text within double quotes. C/C++ Code #include &lt;stdio.h&gt; int main() { pri
6 min read
How will you show memory representation of C variables?
Write a C program to show memory representation of C variables like int, float, pointer, etc. Algorithm: Get the address and size of the variable. Typecast the address to char pointer. Now loop for size of the variable and print the value at the typecasted pointer.Program: C/C++ Code #include &amp;lt;stdio.h&amp;gt; typedef unsigned char *byte_poin
1 min read
C | Dynamic Memory Allocation | Question 1
The most appropriate matching for the following pairs (GATE CS 2000) X: m=malloc(5); m= NULL;        1: using dangling pointers Y: free(n); n-&gt;value=5;         2: using uninitialized pointers Z: char *p; *p = ’a’;           3. lost memory is: (A) X—1 Y—3 Z-2 (B) (X—2 Y—1 Z-3 (C) X—3 Y—2 Z-1 (D) X—3 Y—1 Z-2 Answer: (D) Explanation: X -&gt; A poin
1 min read
C | Dynamic Memory Allocation | Question 2
Consider the following three C functions : [PI] int * g (void) { int x= 10; return (&amp;x); } [P2] int * g (void) { int * px; *px= 10; return px; } [P3] int *g (void) { int *px; px = (int *) malloc (sizeof(int)); *px= 10; return px; } Which of the above three functions are likely to cause problems with pointers? (GATE 2001) (A) Only P3 (B) Only P1
1 min read
three90RightbarBannerImg