×

Memory layout in C

Memory layout in C

The C language is designed so that it becomes easier for a programmer to decide the amount of memory they want to use in a program.

Memory Layout In C

C program consists of:

  • Text segment
  • Initialized data segment
  • Uninitialized data segment
  • Heap
  • Stack

Text Segment:

  • A text segment called a text/code segment is one of the sections of a program present in an object file or a memory containing executable instructions.
  • Text segments consist of binary of a compiled program. In other words, it contains machine codes of a compiled program.
  • The diagram shown above can be placed below a heap or a stack which in later stages prevents overflow of heap and stack from overwriting it.
  • Code segment consists of code that is read-only to prevent the program from modifying the instructions.
  • Text segments are sharable; hence only a single copy can be present in the memory for executed programs, like text editors, C compiler, shells, etc.
  • These are the low addresses present.

Initialized Data:

  • Data segments store program data in the form of initialized or uninitialized variables.
  • The initialized data segment, also known as the data segment, is a part of the program's virtual address space containing global, static, constant, and external (declared and defined using extern keyword) variables, which are initialized by a programmer beforehand.
  • The size of the data segment is directly proportional to the size of values in a program's source code which does not change at run time.
  • This segment of data needs to be altered at run time. Hence it has both read-only and write-only permissions. While variables initialized using constant keyword (const) will apply to read-only,

Eg:

const char* string = "Java_T_Point"  //this will be stored in a read-only area.
 

Data segment can be further grouped into:
Initialized read-only area and
Initialized read-write area.

Eg:

#include <stdio.h>
char c[] = "Java_T_Point";  // initialized global variable in read-write area
const char ch[] = "Hello"; // initialized global variable in read-only area
int main(void)
{
            static int a = 10; // static variable which is an initialized data segment
            return 0;
}

Uninitialized Data Segment:

  • In contrast to the initialized data segment, the uninitialized data segment is generally called the "bss" segment, named after an ancient assembler operator of the name "block started by symbol."
  • BSS will be included with all the uninitialized global, static, and extern (extern keyword) variables.
  • The kernel initializes an uninitialized data segment to arithmetic 0 before the compiler starts the execution. The pointer will be a null pointer; hence, it will not occupy actual space in an object file.
  • When the program is loaded, the program loader will allocate the required memory.
  • BSS starts at the end of a data segment and consists of all the global and the static variables that will be initialized to zero or will not have explicit initialization in the source code.

Eg: 

static int j;
and 
int k; //global variable

Here both will be contained in the BSS segment.

Eg:

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

Heap:

  • Heap is a segment in which dynamic memory allocation takes place.
  • This particular area begins at the end of the BSS segment, and the addresses usually grow upward from that.
  • Heap is managed by malloc, realloc, and free, which uses "brk" and "sbrk" to adjust the size. " brk()" sets the end of a data segment by address while sbrk increments a program's data space by some increment bytes.
  • The Heap area is generally shared by most of the libraries and other dynamically loaded modules in a process.
  • It is used to allocate memory at run time.
  • The heap grows and shrinks in the opposite direction of that of a stack; they are present at the opposite ends of the process's virtual address space.
  • It is also a part of the RAM (Random Access Memory), where dynamically allocated memory is stored.

Eg:

#include <stdio.h>
int main()
{
char *p = malloc(sizeof(char)*4); //allocation of memory in heap
return 0;
}

Stack:

  • Stack is used in storing all local variables and passing arguments to the functions with the instruction's return address.
  • All local variables will be stored in the stack.
  • The stack area is traditionally adjoined to the heap area and grows in the opposite direction; when the stack meets the heap pointer, free memory will be exhausted.
  • The stack area works on the principle LIFO (Last In First Out); that is, the elements will be added to the top of the stack, and the topmost element will be popped out in the first place. It will be located in higher parts of memory. On a standard PC 8086 computer architecture, it grows towards zero; yet in some architectures, it grows in other directions.
  • The stack pointer register tracks the top of a stack. It will change the value every time a value is pushed into the stack.
  • The set of values pushed in one function is called a stack frame; it consists of return addresses.
  • Stack usually comes below the OS (Operating System) kernel, and it grows downwards to lower addresses.
  • Automatic variables will be stored along with information that will be saved each time a function is called; each time it is called, the address of where to return and the information about the environment will be saved on the stack. The new called function allocates room on the stack for its automatic and other temporary variables. This is how recursive functions work.
  • Every time a recursive function is called, a new stack frame is used, so that interference between variables does not happen.

Memory allocation is mainly used for protection. An executable file will be created and treated as a process by the OS; it should have its own address space to avoid any conflicts between data and code in a single program.


Related Topics

How to lock top row in Excel

How to lock top row in excel While working with an Excel spreadsheet, the user utilizes the rows and columns to enter the details under various headings. Sometimes while scrolling the...

4 minutes read.

Bank Account System in C using File Handling

This tells about the creation of bank account system using the C language and handling of files in C. Approach Let us see the approaches and the functions how they are covering...

5 minutes read.

fgets() function in C

fgets() function is present in standard input and output library i.e, stdio.h library. It is a built-in function or pre-define function. It is used to read the specified stream from...

4 minutes read.

Type qualifiers in C

Type qualifiers in C: In the C programming language, type qualifiers are the keywords that prepend to the variables to change their accessibility, i.e., we can tell that the type...

4 minutes read.

C Programming Tutorial

What is C Programming C is most popular and widely used computer programming language. It was developed by Dennis Ritchie in 1972 at the Bell Lab. It is used to develop system application software. There...

8 minutes read.

Advantages of Dynamic Memory Allocation in C

Dynamic Memory Allocation Dynamic memory allocation is a process of assigning or allocating memory to a variable during the execution of a program. Dynamic memory allocation provides storage according to the...

3 minutes read.

What is Linked List in C

Linked list Similar to an array, a linked list is a linear data structure that stores a chain of nodes with two fields of memory in each node. Where first memory...

7 minutes read.

abs() function in C

abs() function is a built-in function present in the stdlib.h header file. It returns an integer value. abs() function converts a negative value into a positive value. For example, if...

4 minutes read.

If Statement in C

Decision Control Statements We frequently desire one set of instructions to be carried out in one circumstance while another set of instructions to be carried out in a completely different circumstance....

3 minutes read.

Assert() Function in C

Assert (): In C, the statements are executed with the exit statement. In C language declare, and it tests the condition parameters. If the statement executed will be false, it...

3 minutes read.

Math functions in C

Math functions in C: In the C programming language, the compiler allows the developer to perform mathematical operations through the header’s functions, represented by <math.h>. The <math.h> header defines various mathematical...

3 minutes read.

Do WHILE LOOP in C Programming Examples

Before understanding the programming examples of the Do-While loop, we have to know what is Do-While loop in C. So, let's start with the definition of the Do-While loop. What is...

5 minutes read.

Explain the Increment and Decrement Operators in C

In the C programming language, the increment operator (++) and the decrement operator (--) are used to increase or decreasing a variable’s value by 1, respectively. The increment operator is written...

10 minutes read.

Armstrong Number in C

The Armstrong number is defined as the sum of each of its digits to the power of the number base for the each given number with any given number base....

3 minutes read.

C Switch Statements

Switch-case statement comes under the Selection control statement; there are four types of Control statements Decision-making statements (if, if-else)Selection statements (Switch-case)Iteration statements (for, while, do-while)Jump statements (break, continue, goto) If we want...

4 minutes read.

Flow Chart of Do while loop in C

This is a flowchart that represents the process of executing the Do while loop in the C programming language Generally, as we know there are three main components of Do While...

3 minutes read.

Bank management system in C

This is a mini project that is constructed completely using the C language. The bank management system is a beginner friendly project. To construct this user only needs to know...

12 minutes read.

How to Find Square Free Numbers in C?

Introduction Square-free number program is a typical interview and academic question in C Programming. In this section, we will define square-free integers, construct algorithms and C program to print the nth...

11 minutes read.

C Program for Extended Euclidean algorithms

The Euclidean method simply computes the GCD (greatest common divisor) of two numbers, p and q. (Let's assume) The GCD of two integers is the greatest number that divides them both....

3 minutes read.

GCD program of two numbers in C

GCD stands for Greatest Common Divisor, which is also known as Highest Common Factor, which can be abbreviated as HCF. Mathematically it can be defined as any two positive integers...

3 minutes read.