Dynamic Memory Allocation in C
Static Memory Allocation
Definition: Memory is allocated at compile-time.
Memory Size: Fixed — you must know the size in advance.
Allocated By: Compiler.
Lifetime: Exists throughout the program’s lifetime.
Speed: Faster since allocation happens once at compile-time.
What is Dynamic Memory Allocation?
Dynamic memory allocation in C allows programmers to allocate memory during runtime,
using pointers. This is useful when the amount of memory required is not known at compile
time.
Why Use It?
Efficient memory usage.
Allocate memory as needed.
Create data structures like arrays, linked lists, trees, etc., dynamically.
� Functions Used for Dynamic Memory Allocation
Function Description
malloc() Allocates specified bytes and returns a void pointer
calloc() Allocates memory for a block of data, initializes all bytes to zero
realloc() Reallocates memory to resize previously allocated memory
free() Frees dynamically allocated memory
What is malloc()?
malloc() stands for memory allocation.
It is used to dynamically allocate memory at runtime from the heap.
Syntax:
pointer = (data_type *)malloc(number_of_bytes);
It returns a pointer to the first byte of the allocated memory block.
Basic Example Using malloc()
� Program to Allocate Memory for n Integers and Store User Input
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *arr;
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
// Allocate memory for n integers
arr = (int *)malloc(n * sizeof(int));
// Check if memory allocation was successful
if (arr == NULL)
{
printf("Memory allocation failed!\n");
return 1;
}
// Read values into the dynamically allocated array
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++)
{
scanf("%d", arr+i);
}
// Display the values
printf("You entered: ");
for (int i = 0; i < n; i++)
{
printf("%d ", *(arr+i));
}
// Free the allocated memory
free(arr);
return 0;
}
Dynamic Memory Allocation
Definition: Memory is allocated at run-time.
Memory Size: Can be determined during program execution.
Allocated By: Programmer using library functions.
Lifetime: Until you explicitly free the memory.
Speed: Slower than static allocation due to run-time processing.