memory layout in c

Memory Layout in C

In C, the memory layout consists of several segments, each serving a specific purpose. These segments include the text segment, data segment, bss segment, heap, and stack.

Text Segment: - The text segment, also known as the code segment, contains the executable code of the program. - It is typically read-only and stores the machine code of the compiled program. - Any attempt to modify the text segment results in a segmentation fault. - The text segment is shared among multiple instances of the same program to save memory.

Data Segment: - The data segment contains initialized static variables and global variables. - It is further divided into initialized read-only area and initialized read-write area. - The initialized read-only area stores constants and strings, while the initialized read-write area stores initialized global and static variables.

BSS Segment: - The BSS (Block Started by Symbol) segment contains uninitialized global and static variables. - It is initialized to zero by the kernel before the program starts executing.

Heap: - The heap is the area of memory used for dynamic memory allocation. - It is managed by functions like malloc, calloc, realloc, and free. - The heap grows dynamically during program execution as memory is allocated and released.

Stack: - The stack is used for local variables, function parameters, return addresses, and bookkeeping information. - It grows and shrinks as functions are called and return. - The stack operates in a last-in, first-out manner.