Allocation of Memory in C
Let us understand the layout of Memory in C. There are basically 4 main segments in a C Program:
- Data Segment
- Code Segment
- Stack Segment
- Heap Segment
Data Segment: The data segment is to hold the value of those variables that need to be available till the end of the program or throughout the lifetime of the program. The Global variables whose life span is complete program will definitely be allocated in Data Segment. Then comes the local variables but declared as static. The lifetime of a local static variable is that of the lifetime of the program they also come in data segment. So we can say that all the:
1) Global Variables
2) Local static variables
Are allocated in Data segment
Code Segment: The program code is where the executable code is available for execution. This are is also known as the ‘text segment’ and is of fixed size. Another important piece of information to take note of here is that the system may consider this area as a ‘read only’ memory area, and any attempt to write in this area can lead to undefined behavior.
The C complier converts executable statements in a C program- such as printf(“C Program”);- into machine code, they are loaded in the code segment.
Stack and Heap Segment: Stack frames are created in the stack for functions and in the heap for dynamic memory allocation.
The stack and heap are uninitialized areas. The local variables are function arguments are allocated in the stack.
When we do dynamic memory allocation such as the use of the malloc function, memory is allocated in the heap are.
1) Global Variables
2) Local static variables
Are allocated in Data segment
Code Segment: The program code is where the executable code is available for execution. This are is also known as the ‘text segment’ and is of fixed size. Another important piece of information to take note of here is that the system may consider this area as a ‘read only’ memory area, and any attempt to write in this area can lead to undefined behavior.
The C complier converts executable statements in a C program- such as printf(“C Program”);- into machine code, they are loaded in the code segment.
Stack and Heap Segment: Stack frames are created in the stack for functions and in the heap for dynamic memory allocation.
The stack and heap are uninitialized areas. The local variables are function arguments are allocated in the stack.
When we do dynamic memory allocation such as the use of the malloc function, memory is allocated in the heap are.
Labels: C Memory

0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home