Tag Archives: memory layout

Memory layout C program

Depending on the data segmentation that a particular processor follows, there are  five segments:

Code Segment (Text Segment)– Stores only code{Executable instructions}, ROM ,shared

2) BSS (or Block Started by Symbols) segment – Stores uninitialized global and static variables ,initialized to zero or do not have explicit initialization in source code

3) Heap segment – all dynamic allocations happens here

4) Stack segment – stores all the local variables and other information’s regarding function return address etc .

Mainly ,Stack and heap grows in opposite direction

Stack grows towards zero from a higher memory address

Stack frame – stores values and return address for one function call.
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) Data segment – stores initialized global and static variables .

Every segment has a write protected region where all the constants are stored. This segment can be further classified into initialized read-only area and initialized read-write area.

For instance, if I have a const int which is local variable, then it is stored in the read only region of stack segment.

Example:

const char* str = “hello world” makes the string literal “hello world” to be stored in initialized read-only area and the character pointer variable str in initialized read-write area.
Check memory layout of a program on linux:

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

Useful Example:

char* string = “hello world” ;
const int a=5;

a=6 // modification of variable “a” gives compilation error but
string[0]=’m’ // or *string=’m’ gives segmentation fault why ??
If we do a=6 we are directly modifying the const but for string[0]=’m’ we are modifying a constant using a non constant.

char s[] = “hello world” – compiler is free to place the string literal. If it is local to function, “hello world” will be copied from “read only” data section to stack of the function. // It will be there in both data and stack segment.
String literals are (commonly) read-only and an attempt to modify will cause the segmentation fault
Hence it is good practice to make big tables or strings static to the function (No copy is required). — Since static won’t be stored in stack

Few more examples:

/* TEXT Segment- As good as integer literal */
static const int read_only_global = 10; // so stored in global. As scope is not limited

/* Initialized DATA Segment*/
int read_write_global = 100;

int main(int argc, char *argv[], char *evn[])
{
/* BSS Segment */
    int static localized_global;

return 0;
}