Memory management in C refers to the allocation and deallocation of memory
during the execution of a program. C provides several built-in functions for
dynamic memory management. Proper management of memory is critical for
efficient and reliable program execution, as failure to manage memory effectively
can lead to memory leaks, segmentation faults, and other issues.
In C, memory is managed in two main ways:
1. Static Memory Allocation: Memory is allocated at compile time, and its size
and structure are fixed.
2. Dynamic Memory Allocation: Memory is allocated at runtime, and its size
can be changed during program execution.
1. Static Memory Allocation
In static memory allocation, the size of the memory is fixed at compile time, and
the memory is allocated for variables at the time of declaration.
#include <stdio.h>
int main() {
int x = 10; // Static memory allocation for variable 'x'
printf("Value of x: %d\n", x);
return 0;
}
In this case, the variable x is allocated a fixed memory location, and its value
remains constant throughout the program’s execution.
2. Dynamic Memory Allocation
Dynamic memory allocation allows you to allocate memory at runtime, which
means you can allocate memory based on user input or other runtime conditions.
, Dynamic memory allocation is useful when you don’t know how much memory
you’ll need at compile time.
C provides four standard functions for dynamic memory allocation:
malloc(): Allocates a block of memory.
calloc(): Allocates memory for an array of elements and initializes them to
zero.
realloc(): Resizes a previously allocated block of memory.
free(): Deallocates previously allocated memory.
3. malloc() (Memory Allocation)
The malloc() function allocates a specified number of bytes of memory and
returns a pointer to the first byte of this memory block. If the memory allocation
fails, it returns NULL.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
// Allocating memory for an integer
ptr = (int *)malloc(sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
*ptr = 100; // Assign a value to the allocated memory
printf("Value: %d\n", *ptr);
// Free the allocated memory
free(ptr);