Dynamic Memory Allocation in C

Dynamic Memory Allocation in C


Introduction

In C programming, memory can be allocated in two ways:

  • Static (compile-time)
  • Dynamic (run-time)

👉 Dynamic Memory Allocation (DMA) allows memory to be allocated during program execution.


What is Dynamic Memory Allocation?

DMA is:
👉 Allocating memory at runtime using functions


Why Use DMA?

  • ✔ Efficient memory usage
  • ✔ Allocate memory as needed
  • ✔ Handle large data
  • ✔ Flexible programming

Header File

#include <stdlib.h>

Dynamic Memory Functions

  • malloc()
  • calloc()
  • realloc()
  • free()

1. malloc()

👉 Allocates memory (uninitialized)

#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr;

ptr = (int*) malloc(5 * sizeof(int));

if (ptr == NULL) {
printf("Memory not allocated");
return 0;
}

ptr[0] = 10;
ptr[1] = 20;

printf("%d %d", ptr[0], ptr[1]);

free(ptr);

return 0;
}

Output

10 20

2. calloc()

👉 Allocates memory and initializes to 0

#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr;

ptr = (int*) calloc(3, sizeof(int));

for (int i = 0; i < 3; i++) {
printf("%d ", ptr[i]);
}

free(ptr);

return 0;
}

Output

0 0 0

3. realloc()

👉 Resizes allocated memory

#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr;

ptr = (int*) malloc(2 * sizeof(int));

ptr[0] = 5;
ptr[1] = 10;

ptr = (int*) realloc(ptr, 4 * sizeof(int));

ptr[2] = 15;
ptr[3] = 20;

for (int i = 0; i < 4; i++) {
printf("%d ", ptr[i]);
}

free(ptr);

return 0;
}

Output

5 10 15 20

4. free()

👉 Deallocates memory

free(ptr);

👉 Prevents memory leaks


DMA Functions Table

Function Purpose
malloc() Allocate memory
calloc() Allocate & initialize
realloc() Resize memory
free() Deallocate memory

Important Notes

  • Always check for NULL
  • Free memory after use
  • Avoid memory leaks
  • Use correct size

Common Mistakes

  • ❌ Not freeing memory
  • ❌ Using uninitialized memory
  • ❌ Wrong size allocation
  • ❌ Memory leaks

Pro Tips

  • ✔ Always use free()
  • ✔ Check pointer before use
  • ✔ Use calloc() when needed
  • ✔ Practice dynamic arrays

Conclusion

Dynamic Memory Allocation allows flexible and efficient memory usage in C programming. It is essential for advanced applications.

Master DMA to handle memory effectively.

👉 This article is part of Dharani Tech Edu Hub — where learning programming is made simple and practical.

Comments

Popular posts from this blog

Introduction to C Programming

Operators in C

Input & Output in C