Memory Layout in C
×


Memory Layout in C

48

  Memory layout in C refers to the organization and segmentation of memory during program execution.

 The memory is typically divided into various segments: stack, heap, data segment, and code/text segment.

 Understanding this layout helps in efficient memory management and debugging.

1Code/Text Segment:

 Contains the executable code of the program.

 Typically read-only and shared among multiple instances of the program.


2Data Segment:

 Global Variables: Variables declared outside functions.

 Static Variables: Variables declared with the static keyword.

 Constants: Memory for constants like string literals.


3Heap:

 Dynamic memory allocation area.

 Managed by functions like malloc(), calloc(), realloc(), and free().

 Memory allocation and deallocation can happen in any order.


4Stack:

 Stores local variables and function call information.

 Managed automatically by the CPU.

 Memory allocation and deallocation in the stack follow a Last-In-First-Out (LIFO) order.

// Program for Memory layout in C
#include<stdio.h> 
#include<stdlib.h> 

// Global variable (Data Segment)
int global_var = 10;

int main() {
    // Local variable (Stack)
    int local_var = 20;

    // Dynamic memory allocation (Heap)
    int *ptr = (int *) malloc(sizeof(int));
    *ptr = 30;

    // Printing addresses
    printf("Address of global_var: %p\n", &global_var);
    printf("Address of local_var: %p\n", &local_var);
    printf("Address stored in ptr: %p\n", ptr);

    // Freeing allocated memory
    free(ptr);

    return 0;
}
	

Output:

Address of global_var: 0x404040
Address of local_var: 0x7ffdde62cde4
Address stored in ptr: 0x20972a0

 global_var: A global variable stored in the Data Segment.

 local_var: A local variable stored in the Stack.

 ptr: A pointer variable pointing to memory allocated in the Heap using malloc().

 The program prints the addresses of these variables to show where they are stored in memory.

 After allocating memory on the heap using malloc(), the program frees the allocated memory using free().



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments