Memory Layout of C Programs - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Memory Layout of C Programs

Share This

You have written many programs in C Language. So, it's time to understand memory layout of a program. Memory representation of a C program consists of the following sections.

  • Text Segment / Code Block
  • Initialized Data Segment / Data Segment
  • Uninitialized Data Segment / Block Started by Symbol (BSS)
  • Stack Memory
  • Heap Memory


Text Segment

A text segment, also known as a code segment or simply as text, consists of executable instructions of a program in an object file or in memory. This segment is read-only for preventing from accidental modifications. It's allocated below the heap or stack so that in case of heap and stack overflow it's not overwritten.


Initialized Data Segment

Initialized Data Segment (Data Segment) is a portion of the virtual address space of a program that contains initialized global and static variables (initialized by the programmer). Unlike Text Segment, it's not read-only memory, as the values may change during run-time.

Example: static int i = 10; and global int i = 10;


Uninitialized Data Segment

It's also known as BSS segment, named after an ancient assembler operator that stood for Block Started by Symbol. This segment is allocated just after Data Segment. The kernel initializes the values to arithmetic 0 before executing them. The global and static variables which are initialized to zero or do not have explicit initialization in source code are allocated here.

Example: static int i; and global int j;


Stack Memory

Stack memory is used to store automatic variables, along with information of a called function. When a function is called, the state of the caller along with the address where the called function will return, are stored into the stack. Then the new space is allocated for the state of the called function. Using the special register, stack pointer, the top element of the stack is tracked.


Heap Memory

Dynamic memory allocation (using malloc, realloc, and free functions) is usually taken place in Heap area. It begins at the end of the BSS segment and grows towards larger addresses. The Heap area is shared by all shared libraries and dynamically loaded modules in a process.


To analyze different types of memory areas, you may use size command as shown below.

#include<stdio.h>

int x;
int z = 10;

int main()
{
        int p;
        char q;

        printf("Helllo World!");
        return 0;
}

void function()
{
        static int y;
        int r;
}

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.