Apply Now Apply Now Apply Now
header_logo
Post thumbnail
PROGRAMMING LANGUAGES

Dynamic Memory Allocation in C

By Vishalini Devarajan

Memory management is a key concept in C programming. Often, programmers do not know the exact amount of memory needed before a program starts running. This is where dynamic memory allocation is helpful.

Dynamic memory allocation in C allows programs to request memory while running, rather than reserving it all at compile time. This approach offers flexibility, improves memory use, and supports scalable applications.

In this article, we will examine the four dynamic memory allocation functions in C and understand their roles in managing memory effectively.

Table of contents


  1. TL;DR
  2. Why Dynamic Memory Allocation is Needed
  3. Memory Areas in C
  4. Header File Required
  5. malloc() Function in C
    • Syntax
    • Example Program
    • Output
  6. calloc() Function in C
    • Syntax
    • Example Program
    • Output
  7. realloc() Function in C
    • Syntax
    • Example Program
    • Output
  8. free() Function in C
    • Syntax
    • Example
  9. Real World Applications of Dynamic Memory Allocation
  10. Common Mistakes in Dynamic Memory Allocation
  11. Best Practices for Dynamic Memory Allocation
  12. Static vs Dynamic Memory Allocation
  13. Advantages of Dynamic Memory Allocation
  14. Disadvantages of Dynamic Memory Allocation
  15. Conclusion
  16. FAQs
    • What is dynamic memory allocation in C?
    • Which header file is used for dynamic memory allocation?
    • What is the difference between malloc() and calloc()?
    • Why is free() important in C?
    • What happens if malloc() fails?
    • Where is dynamically allocated memory stored?
    • Can realloc() resize allocated memory?
    • What is a memory leak in C?
    • Why is dynamic memory allocation important?
    • Is dynamic memory allocation used in real applications?

TL;DR

  1. Dynamic memory allocation in C allocates memory during runtime.
  2. The main functions used are malloc(), calloc(), realloc(), and free().
  3. It helps reduce memory waste and improves flexibility.
  4. Dynamic memory allocation is common in data structures and system-level applications.

Why Dynamic Memory Allocation is Needed

Dynamic memory allocation allocates memory during runtime instead of at compile time. It lets programs request memory only when it’s needed, helping manage memory efficiently during execution. This provides flexibility and allows programs to respond to changing data needs.

Memory Areas in C

A C program primarily utilizes two main memory areas: stack memory and heap memory.

Stack memory holds local variables and function calls, while heap memory is used for dynamic memory allocation.

When memory is allocated using functions like malloc() or calloc(), that memory is created in the heap.

Header File Required

To use dynamic memory allocation functions, you need to include the following header file:

#include <stdlib.h>

1. malloc() Function in C

The malloc() function stands for memory allocation. It allocates a block of memory at runtime.

The allocated memory initially contains garbage values because it is not automatically initialized.

Syntax

ptr = (datatype*) malloc(size_in_bytes);

Example Program

#include <stdio.h>

#include <stdlib.h>

int main() {

int *ptr;

int n = 5;

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

if(ptr == NULL) {

printf(“Memory allocation failed”);

return 1;

}

for(int i = 0; i < n; i++) {

ptr[i] = i + 1;

}

printf(“Array elements:\n”);

for(int i = 0; i < n; i++) {

printf(“%d “, ptr[i]);

}

free(ptr);

return 0;

}

Output

Array elements:

1 2 3 4 5

The malloc() function is useful when the memory size is unknown before execution. It returns NULL if memory allocation fails.

2. calloc() Function in C

The calloc() function allocates memory for multiple elements and initializes all allocated bytes to zero.

Unlike malloc(), the memory returned by calloc() does not contain garbage values initially.

Syntax

ptr = (datatype*) calloc(number_of_elements, size_of_each_element);

Example Program

#include <stdio.h>

#include <stdlib.h>

int main() {

int *ptr;

int n = 5;

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

if(ptr == NULL) {

printf(“Memory allocation failed”);

return 1;

}

printf(“Values after calloc:\n”);

for(int i = 0; i < n; i++) {

printf(“%d “, ptr[i]);

}

free(ptr);

return 0;

}

Output

Values after calloc:

0 0 0 0 0

The main advantage of calloc() is automatic initialization, which helps avoid unpredictable behavior caused by garbage values.

3. realloc() Function in C

The realloc() function is used to resize previously allocated memory.

It can increase or decrease the size of an existing memory block while the program is running.

Syntax

ptr = realloc(ptr, new_size);

Example Program

#include <stdio.h>

#include <stdlib.h>

int main() {

int *ptr;

int n = 3;

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

for(int i = 0; i < n; i++) {

ptr[i] = i + 1;

}

n = 5;

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

for(int i = 3; i < n; i++) {

ptr[i] = i + 1;

}

printf(“Updated array:\n”);

for(int i = 0; i < n; i++) {

printf(“%d “, ptr[i]);

}

free(ptr);

return 0;

}

MDN

Output

Updated array:

1 2 3 4 5

The realloc() function keeps existing data while changing the memory size. However, if resizing fails, it may return NULL.

4. free() Function in C

The free() function releases dynamically allocated memory back to the system.

Syntax

free(ptr);

Example

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

free(ptr);

If allocated memory is not released properly, memory leaks can occur. Memory leaks can gradually reduce available system memory and affect program performance.

Real World Applications of Dynamic Memory Allocation

Dynamic memory allocation is widely used in modern software systems where data size changes during execution.

Linked lists use dynamic memory to create nodes as needed. Dynamic arrays can increase memory size based on user input. Operating systems also allocate memory dynamically for running processes and applications.

Database systems, gaming engines, file management systems, compilers, and networking applications all rely on runtime memory allocation.

Common Mistakes in Dynamic Memory Allocation

One common mistake is forgetting to free allocated memory.

Example:

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

If free(ptr) is not called later, the memory remains occupied even after it is no longer needed.

Another mistake is accessing memory after freeing it.

free(ptr);

printf(“%d”, ptr[0]);

This causes undefined behavior because the memory has already been released.

Programmers should also check whether allocation functions return NULL before using allocated memory.

You can also explore HCL GUVI’s DSA ebook to understand how concepts like dynamic memory allocation are used in linked lists, trees, stacks, and queues. 

Best Practices for Dynamic Memory Allocation

Always use sizeof() when allocating memory because it improves portability and accuracy.

Correct approach:

malloc(n * sizeof(int));

Always check if allocation succeeded before accessing memory.

if(ptr == NULL);

Memory should always be released after use.

free(ptr);

After freeing memory, setting the pointer to NULL helps prevent accidental access to invalid memory.

ptr = NULL;

Static vs Dynamic Memory Allocation

Static memory allocation happens during compile time and typically uses stack memory.

Dynamic memory allocation occurs during runtime and uses heap memory.

Static allocation is faster but less flexible, while dynamic allocation offers flexibility but requires manual memory management. Dynamic allocation is crucial when the amount of data changes at runtime.

Advantages of Dynamic Memory Allocation

Dynamic memory allocation enhances memory efficiency because it allocates memory only when necessary.

It provides runtime flexibility, supports scalable applications, and enables complex data structures like linked lists, trees, queues, and graphs.

Programs can be more adaptable since the memory size can grow or shrink dynamically.

Disadvantages of Dynamic Memory Allocation

Dynamic memory allocation is slower than static allocation since memory management occurs during runtime.

Improper handling may lead to memory leaks, dangling pointers, fragmentation, and runtime errors.

Since memory management is manual in C, programmers must carefully handle allocation and deallocation.

Curious about how these concepts work in real-world applications? Join HCL GUVI’s C Programming course to build projects and learn programming concepts used in backend and web development.

Conclusion

Dynamic memory allocation is a vital concept in C programming that helps programs manage memory efficiently during runtime.

Functions like malloc(), calloc(), realloc(), and free() provide flexibility and allow applications to handle varying amounts of data dynamically.

Understanding how these functions work is essential for system programming, data structures, operating systems, embedded systems, and high-performance applications.

Mastering dynamic memory allocation helps programmers create optimized, scalable, and memory-efficient C programs.

FAQs

What is dynamic memory allocation in C?

Dynamic memory allocation is the process of allocating memory during runtime using functions like malloc(), calloc(), realloc(), and free().

Which header file is used for dynamic memory allocation?

The stdlib.h header file is required.

What is the difference between malloc() and calloc()?

malloc() allocates uninitialized memory, while calloc() allocates memory and initializes all bytes to zero.

Why is free() important in C?

The free() function releases allocated memory and prevents memory leaks.

What happens if malloc() fails?

If allocation fails, malloc() returns NULL.

Where is dynamically allocated memory stored?

Dynamically allocated memory is stored in the heap.

Can realloc() resize allocated memory?

Yes, realloc() can increase or decrease the size of allocated memory.

What is a memory leak in C?

A memory leak occurs when allocated memory is not released properly using free().

Why is dynamic memory allocation important?

It helps programs manage varying amounts of data efficiently during execution.

MDN

Is dynamic memory allocation used in real applications?

Yes, it is commonly used in operating systems, databases, compilers, browsers, networking software, and data structures.

Success Stories

Did you enjoy this article?

Schedule 1:1 free counselling

Similar Articles

Loading...
Get in Touch
Chat on Whatsapp
Request Callback
Share logo Copy link
Table of contents Table of contents
Table of contents Articles
Close button

  1. TL;DR
  2. Why Dynamic Memory Allocation is Needed
  3. Memory Areas in C
  4. Header File Required
  5. malloc() Function in C
    • Syntax
    • Example Program
    • Output
  6. calloc() Function in C
    • Syntax
    • Example Program
    • Output
  7. realloc() Function in C
    • Syntax
    • Example Program
    • Output
  8. free() Function in C
    • Syntax
    • Example
  9. Real World Applications of Dynamic Memory Allocation
  10. Common Mistakes in Dynamic Memory Allocation
  11. Best Practices for Dynamic Memory Allocation
  12. Static vs Dynamic Memory Allocation
  13. Advantages of Dynamic Memory Allocation
  14. Disadvantages of Dynamic Memory Allocation
  15. Conclusion
  16. FAQs
    • What is dynamic memory allocation in C?
    • Which header file is used for dynamic memory allocation?
    • What is the difference between malloc() and calloc()?
    • Why is free() important in C?
    • What happens if malloc() fails?
    • Where is dynamically allocated memory stored?
    • Can realloc() resize allocated memory?
    • What is a memory leak in C?
    • Why is dynamic memory allocation important?
    • Is dynamic memory allocation used in real applications?