Explain dynamic memory allocation in C with an example

Dynamic memory allocation in C allows programmers to allocate and deallocate memory during program execution rather than at compile time. This provides flexibility to handle varying data sizes efficiently.

Syntax

void* malloc(size_t size);
void* calloc(size_t num, size_t size);
void* realloc(void* ptr, size_t new_size);
void free(void* ptr);

Dynamic Memory Allocation Functions

The main functions used for dynamic memory allocation in C are −

  • malloc() − allocates a block of memory in bytes at runtime
  • calloc() − allocates continuous blocks of memory and initializes them to zero
  • realloc() − used to resize previously allocated memory
  • free() − deallocates previously allocated memory space

Example: Sum of n Numbers Using Dynamic Allocation

The following program demonstrates dynamic memory allocation to find the sum of n numbers entered by the user −

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

int main() {
    int n, i, sum = 0;
    int *ptr;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    // Allocating memory dynamically using malloc()
    ptr = (int *)malloc(n * sizeof(int));
    
    // Check if memory allocation was successful
    if (ptr == NULL) {
        printf("Memory allocation failed!<br>");
        return 1;
    }
    
    printf("Enter %d elements:<br>", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &ptr[i]);
        sum += ptr[i];
    }
    
    printf("The sum of elements is: %d<br>", sum);
    
    // Free the allocated memory
    free(ptr);
    
    return 0;
}
Enter the number of elements: 5
Enter 5 elements:
10
20
30
40
50
The sum of elements is: 150

Key Points

  • Always check if malloc() returns NULL to handle memory allocation failure
  • Use free() to deallocate memory and prevent memory leaks
  • After calling free(), accessing the pointer leads to undefined behavior
  • Dynamic allocation is useful when the size of data is unknown at compile time

Conclusion

Dynamic memory allocation provides flexibility in memory management, allowing programs to allocate exactly the required memory at runtime. Always remember to free allocated memory to prevent memory leaks.

Updated on: 2026-03-15T13:07:51+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements