Day - 3
Understanding C Memory Layout
Memory in a C program is divided into different sections, each with a specific purpose, which helps the program run efficiently and manage data. Let's go through each section and explain its role with simple examples.
1. Text Segment (Code)
- This section contains the actual machine code, the instructions that tell the computer what to do.
- Here, the compiled machine code for
printf("Hello, World!");
will be stored in the text segment. It's read-only, so it can't be modified during runtime.
Example :
printf("Hello, World!");
2. Initialized Data Segment
- This segment stores global and static variables that are initialized with a value before the program runs.
- Here,
globalVar
andstaticVar
are stored in the initialized data segment because they are global/static and have initial values.
Example :
int globalVar = 10;
static int staticVar = 5;
3. Uninitialized Data Segment (BSS)
- This segment stores global and static variables that are declared but not initialized. They are automatically initialized to zero.
- Both
uninitVar
andstaticUninitVar
will be stored in the BSS segment and initialized to zero.
Example :
int uninitVar;
static int staticUninitVar;
4. Heap
- The heap is a region used for dynamic memory allocation. Variables allocated with functions like
malloc
orcalloc
are stored here. - Here, the memory for the array pointed to by
ptr
is allocated on the heap. This memory must be manually managed, meaning we should usefree(ptr);
to release it when we're done.
Example :
int *ptr = malloc(sizeof(int) * 5);
5. Stack
- The stack stores local variables (variables declared within functions) and keeps track of function calls. Each time a function is called, a new "frame" is added to the stack.
- When
func
is called,localVar
is stored in the stack. Oncefunc
finishes, the memory forlocalVar
is freed automatically.
Example :
void func() {
int localVar = 10;
}
Summary of How Each Part Helps in Coding
- Text Segment: Stores the instructions for the program, keeping your code organized and protected from changes.
- Initialized Data Segment: Allows global and static variables with initial values to persist throughout the program's execution.
- BSS: Handles uninitialized variables automatically, initializing them to zero without needing explicit code.
- Heap: Provides flexible memory that can grow or shrink as needed during runtime, useful for dynamic structures like linked lists or resizable arrays.
- Stack: Manages function calls and local variables automatically, making memory management easy for short-lived variables and supporting function recursion.
Comments
Post a Comment