Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
Diagram for memory structure of C
3.
Segments of the Memory Layout
3.1.
1. Text Segment
3.2.
2. Initialized Data Segment
3.3.
Example
3.4.
C
3.5.
3. Uninitialized Data Segment
3.6.
Example
3.7.
C
3.8.
4. Stack
3.9.
5. Heap
4.
Command-line arguments
5.
Examples of Command-line arguments
5.1.
1. Print the name of the program
5.2.
C
5.3.
2. Get the user's name
5.4.
C
5.5.
3. Calculate the sum of two numbers
5.6.
C
5.7.
4. Open a file and read its contents
5.8.
C
6.
Frequently Asked Questions
6.1.
What does the memory layout of the C program consist of?
6.2.
What is memory mapping in C?
6.3.
What is the memory layout of a process?
6.4.
What are the 4 types of memory in C?
6.5.
What is the memory model in C?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Memory layout of C program

Author Ayushi Poddar
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction 

The executable file is stored in the computer's RAM in an organized manner after a C program is created and runs the memory layout of the C program. 

Memory layout of  C program

The below diagram shows the memory layout of the C program :

Diagram for memory structure of C

diagram of memory layout of the C program
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Segments of the Memory Layout

From the above figure, we can see that the C program consists of the following segments in the memory layout:

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

Let's discuss further regarding these segments of the memory layout.

1. Text Segment

A text segment contains code or simply a text containing executable instructions in an object file or memory. In order to prevent overflowing of stack or heap, the text section is placed below it in the memory region. Generally, this segment is sharable as only a single copy is stored in the memory for frequently executed programs such as compilers, shells, editors, etc. To prevent a program from unknowingly modifying its instructions, it is kept as read-only.

2. Initialized Data Segment

It is simply called the Data segment and is a part of the virtual address space of a program where static and global variables are initialized by a programmer. Unlike the Text segment, values of variables might need alteration during runtime, so it is not read-only. This segment is further divided into:

  • Initialized read-only area: Values of variables can not be modified here.
  • Initialized read-write area: Values of variables can be modified here.


Example

  • C

C

#include<stdio.h>  

char string[] = "Coding Ninjas Studio";

int main() 



  static int i = 50;   

  return 0;  

}


Explanation

The global variables here like char str[] = “Coding Ninjas Studio’ and int i=50 will be stored in the initialized read-write area in the memory. Suppose, we create the global variable like const char* string1 = "Coding Ninjas Studio"; the literal "Coding Ninjas Studio" would be stored in the initialized read area, whereas the char pointer variable would be stored in the initialized write area.

3. Uninitialized Data Segment

It is often called the “bss” segment (block started by symbol) which stores all uninitialized local, global, and external variables. If they are not initialized, then they are stored with zero value by default. This segment contains the object file where all the statically allocated variables are stored. 


Example

  • C

C

#include<stdio.h>  

char x;  // Uninitialized global variable declared 

int main() 



   static int x; // Uninitialized static variable declared 

   return 0;  

}


Explanation

Here, statically allocated objects are those without explicit initialization that is initialized with zero value. In the above code, x is an uninitialized variable, so it is stored in the uninitialized data section.

4. Stack

The stack frame is used when we define and call that function. The variables, as well as the function arguments defined in that function, are stored in the stack. This type of memory allocation is called Static memory allocation as the size of the variables is defined in the function during compile time. Whenever a function is called, a new stack frame is created, and hence stack plays an important role in the memory. It is commonly used for recursive functions. It also contains a LIFO (last in first out) structure, the program stack typically located in the higher section of memory. 

5. Heap

It is used for dynamic memory allocation. It starts at the end of the bss segment and moves upwards toward higher addresses. The functions like calloc() and malloc() allocate memory in a heap. The dynamically allocated modules and the shared memory use heap memory. To deallocate memory from the heap, the free() function is called. 

Command-line arguments

Command-line arguments are the values which are passed to a program when it is executed. They are specified after the name of the program on the command line. For example, to execute a program called MYapp with two command-line arguments, use the following command:

MYapp arg1 arg2

 

The arguments arg1 and arg2 would then be passed to the MYapp function. In C programming, command-line arguments are passed to the main() function as two variables that are argc and argv.

Examples of Command-line arguments

Here are 4 different examples of command-line arguments in C programming with their solutions:

1. Print the name of the program

  • C

C

#include <stdio.h>

int main(int argc, char *argv[]) {
printf("Program name: %s\n", argv[0]);

return 0;
}


The above code first prints the number of command-line arguments using the argc variable. Then, it prints each of the command-line arguments using the argv variable. The argv[0] variable stores the name of the program itself.

2. Get the user's name

  • C

C

#include <stdio.h>

int main(int argc, char *argv[]) {

printf("What is your name? ");
char name[100];
scanf("%s", name);

printf("Your name is: %s\n", name);

return 0;
}


The above code first prompts the user to enter their name. Then, it uses the scanf() function to read the user's input into the name variable. Finally, it prints the user's name back to the console.

3. Calculate the sum of two numbers

  • C

C

#include <stdio.h>

int main(int argc, char *argv[]) {
FILE *fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}

char buffer[100];
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}

fclose(fp);

return 0;
}


The above code first prompts the user to enter two numbers. Then, it uses the scanf() function to read the user's input into the num1 and num2 variables. Finally, it calculates the sum of the two numbers and prints it back to the console.

4. Open a file and read its contents

  • C

C

#include <stdio.h>

int main(int argc, char *argv[]) {
FILE *fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}

char buffer[100];
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}

fclose(fp);

return 0;
}


The code first opens the file specified by the first command-line argument. Then, it uses a loop to read the contents of the file one line at a time. Finally, it closes the file.

Frequently Asked Questions

What does the memory layout of the C program consist of?

The memory layout of a C program comprises four segments: text (code), data, heap, and stack. The text segment holds the executable code, the data segment stores global and static variables, the heap is for dynamic memory allocation, and the stack manages function calls and local variables.

What is memory mapping in C?

Memory mapping in C refers to the process of associating files with a range of memory, treating them as if they were arrays. This allows direct access and manipulation of file contents in memory, facilitating efficient I/O operations.

What is the memory layout of a process?

The memory layout of a process consists of four main areas: text (code), data, heap, and stack. The text segment stores executable code, the data segment holds global and static variables, the heap manages dynamically allocated memory, and the stack handles function calls and local variables.

What are the 4 types of memory in C?

In C, memory is categorized into four types Stack (manages function calls and local variables), Heap(handles dynamic memory allocation), Data(stores global and static variables) and Code(contains the executable code of the program).

What is the memory model in C?

The memory model in C organizes data in a hierarchical structure, including stack, heap, text, and data segments, to efficiently manage memory allocation, deallocation, and access during program execution.

Conclusion

In this article, we have discussed in detail the about memory layout of a C program and its five segments which are text/code, initialized data, uninitialized data, stack, and heap and looked at each one of them using examples. At last, discussed some of the faqs.

Do check out The Interview guide for Product Based Companies as well as some of the Popular Interview Problems from Top companies like AmazonAdobeGoogle, etc. on Coding Ninjas Studio.

Also check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, etc.

Next article
How to deallocate memory without using free method in C Language?
Live masterclass