Skip to main content

Dynamic Memory Allocation in C (malloc, calloc, realloc, free)

2 min read
Share:
On this page (10sections)

About this page

This page focuses on dynamic (heap) memorymalloc, calloc, realloc and free with code examples. For the broader picture including static and stack memory, see Memory management In C.

Introduction

Stack memory is automatic and limited. Dynamic memory is allocated from the heap at runtime using malloc, calloc, and realloc. You must release it with free to avoid memory leaks.

Key Functions

FunctionPurpose
malloc(size)Allocate uninitialized bytes
calloc(n, size)Allocate and zero-initialize n elements
realloc(ptr, size)Resize existing block
free(ptr)Release memory

All are declared in <stdlib.h>.

Example — malloc and free

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

int main(void) {
    int n = 5, i;
    int *arr = (int *)malloc(n * sizeof(int));

    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    for (i = 0; i < n; i++)
        arr[i] = (i + 1) * 10;

    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);

    free(arr);
    arr = NULL;
    return 0;
}

Sample Output

10 20 30 40 50

calloc Example

int *zeros = (int *)calloc(10, sizeof(int));  /* all bytes set to 0 */

realloc Example

arr = (int *)realloc(arr, 10 * sizeof(int));  /* grow array */
if (arr == NULL) { /* handle failure — original block may still exist */ }

Best Practices

  • Always check for NULL after allocation.
  • Set pointer to NULL after free to avoid double-free bugs.
  • Match every malloc/calloc/realloc with exactly one free.
  • Prefer calloc when you need zero-initialized memory.

Common Mistakes

  • Memory leak — forgetting free.
  • Double free — calling free twice on the same pointer.
  • Dangling pointer — using memory after free.
  • Wrong size — malloc(n) instead of malloc(n * sizeof(type)).

Continue learning with these related tutorials and programs:

Related Tutorials

Search tutorials