C Dynamic Memory Allocation

Normally the size of an array is fixed when we write the program. With dynamic memory allocation we ask for memory while the program runs, so we can use exactly what we need. The functions are in stdlib.h.

The four functions

FunctionWork
malloc(size)Allocates a block of bytes. Values are garbage.
calloc(n, size)Allocates n elements and sets all to 0.
realloc(ptr, size)Changes the size of an old block.
free(ptr)Gives the memory back.

malloc example

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

int main(void) {
    int n = 4;
    int *a = malloc(n * sizeof(int));

    if (a == NULL) {
        printf("Memory not available\n");
        return 1;
    }

    for (int i = 0; i < n; i++) {
        a[i] = (i + 1) * 10;
    }
    for (int i = 0; i < n; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");

    free(a);
    return 0;
}

Output:

Output of the above program is

10 20 30 40

malloc() returns NULL when memory is not available, so always check it. After using the memory, call free().

calloc

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

int main(void) {
    int *a = calloc(3, sizeof(int));

    printf("%d %d %d\n", a[0], a[1], a[2]);
    free(a);
    return 0;
}

Output:

Output of the above program is

0 0 0

realloc: grow the array

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

int main(void) {
    int *a = malloc(2 * sizeof(int));
    a[0] = 1;
    a[1] = 2;

    a = realloc(a, 4 * sizeof(int));   // now 4 elements
    a[2] = 3;
    a[3] = 4;

    for (int i = 0; i < 4; i++) printf("%d ", a[i]);
    printf("\n");

    free(a);
    return 0;
}

Output:

Output of the above program is

1 2 3 4

Common mistakes

  • Memory leak: you forget free(), so memory is lost until the program ends.
  • Use after free: using the pointer after free(). Set it to NULL after freeing.
  • Double free: calling free() two times on the same pointer.
  • Writing outside the allocated size.
Note: In real code, a = realloc(a, ...) can lose the old pointer if realloc fails. Store the result in a temporary pointer first and check it.

Next: C Structures.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.