Dynamic Memory Allocation in C (malloc, calloc)

Dynamic Memory Allocation allows a program to request memory while execution is running. This makes programs flexible when handling unknown or varying amounts of data.

What is Dynamic Memory?

In static memory allocation, memory size is fixed during compile time. Dynamic memory allocation allows you to allocate and release memory at runtime.

Functions Used for Dynamic Memory

malloc()

malloc() stands for "Memory Allocation". It allocates a block of memory and returns a void pointer.

ptr = (int*) malloc(size_in_bytes);

calloc()

calloc() stands for β€œContiguous Allocation”. It allocates multiple memory blocks and initializes all bytes with 0.

ptr = (int*) calloc(number_of_elements, size_of_each);

Difference Between malloc() and calloc()

Memory Allocation Flow

5 Practical Examples of malloc() & calloc()

Example 1 β€” malloc() for Integer Array

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

int main(){

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

    for(int i=0; i<5; i++)
        p[i] = i + 1;

    for(int i=0; i<5; i++)
        printf("%d ", p[i]);

    free(p);

    return 0;
}

Example 2 β€” calloc() Initialize with Zero

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

int main(){

    int *p = (int*) calloc(5, sizeof(int));

    for(int i=0; i<5; i++)
        printf("%d ", p[i]);  // prints 0

    free(p);

    return 0;
}

Example 3 β€” malloc() for Float

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

int main(){

    float *p = (float*) malloc(3 * sizeof(float));

    p[0] = 2.5;
    p[1] = 3.7;
    p[2] = 4.8;

    for(int i=0; i<3; i++)
        printf("%.1f ", p[i]);

    free(p);

    return 0;
}

Example 4 β€” calloc() for String Storage

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

int main(){

    char *name = (char*) calloc(20, sizeof(char));

    strcpy(name, "Sourav Sahu");

    printf("%s", name);

    free(name);

    return 0;
}

Example 5 β€” malloc() and free() Demonstration

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

int main(){

    int *p = (int*) malloc(sizeof(int));

    *p = 100;

    printf("Value = %d\n", *p);

    free(p);

    return 0;
}

Practice Questions

  1. What is dynamic memory allocation?
  2. Explain malloc() and calloc() with differences.
  3. Why is free() important?
  4. What is the meaning of heap memory?
  5. Write advantages of dynamic memory.

Practice Task

Write a C program using malloc() to store 10 integers, find the largest number, and free the allocated memory.