The memory layout of C programs consists of several segments. The segments accessible to a user program are shown in the figure below:

 

Fig. 1 C program memory layout

Code Segment (.text)  

This segment stores the executable program code (the machine instructions). Variables defined with the const type qualifier can also be placed in the code segment. It is a read-only segment stored in a non-volatile memory. Depending on the platform it can be copied to a faster RAM memory or the program code can be executed in place (directly from the non-volatile memory).

Initialized Data Segment (.data)

This segment stores all global variables (with storage class specifier static or extern)1  and local (defined inside a function) static variables that have defined initial values different than zero. The segment’s size is determined by the size of the variables and is know at compile time. This segment can be further classified into initialized read-only area and initialized read-write area (storing data that can be altered at run time). This segment is copied from the non-volatile memory it is initially stored (e.g Flash) to RAM.

Uninitialized Data Segment (.bss)

This segment stores all global and local variables that are initialized to zero or do not have explicit initialization in the source code.  The memory locations of variables stored in this segment are initialized to zero before the execution of the program starts. This is usually performed by the boot code (see our article The Boot Process of a Microcontroller). Since the value of these variables are all zeroes, they do not have to be stored in a non-volatile memory.

Example for initialized and uninitialized data segments:

#include<stdio.h>
int variable_1=192;          /* Placed in initialized data segment */
int variable_2;              /* Placed in uninitialized data segment*/
int variable_3 = 0;          /* Placed in uninitialized data segment*/
int main() { 
static int variable_2=67; /* Static local variable also placed in the initialized data segment */ 
/* ... Function code ... */ 

}

Heap

The heap is a segment of the system memory (RAM) that provides dynamic memory allocation. For more information see our article The Concept of Heap and Its Usage in Embedded Systems.

Stack

In general we can describe the stack segment as a temporary storage for data. For more information see our article The Concept of Stack and Its Usage in Microprocessors.


Footnotes

1. If storage class is not explicitly specified(that is, the extern or static keywords), then by default global variables have external linkage.

Was this article helpful?