C Dynamic Memory Allocation

πŸš€ C Dynamic Memory Allocation

In C, **dynamic memory allocation** allows you to allocate memory at runtime instead of compile time. It gives you control over how much memory to use and when to release it.

The standard library provides these functions from <stdlib.h>:

  • malloc() – Allocates memory block
  • calloc() – Allocates and initializes memory
  • realloc() – Resizes memory block
  • free() – Frees allocated memory

πŸ“ Example: Using malloc()

Allocate memory for 5 integers dynamically using malloc().

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

int main() {
    int *arr;
    int i;

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

    if (arr == NULL) {
        printf("Memory not allocated.\n");
        return 1;
    }

    for (i = 0; i < 5; i++) {
        arr[i] = i + 1;
    }

    printf("Array elements: ");
    for (i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }

    free(arr);
    return 0;
}
  

Try It Now

πŸ“ Example: Using calloc()

calloc() also allocates memory, but initializes all values to 0.

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

int main() {
    int *arr;
    int i;

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

    if (arr == NULL) {
        printf("Memory not allocated.\n");
        return 1;
    }

    printf("Array elements (initialized to 0): ");
    for (i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }

    free(arr);
    return 0;
}
  

Try It Now

πŸ“ Example: Using realloc()

realloc() is used to resize an already allocated memory block.

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

int main() {
    int *arr;
    int i;

    arr = (int*) malloc(3 * sizeof(int));

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

    for (i = 0; i < 3; i++) {
        arr[i] = i + 1;
    }

    arr = (int*) realloc(arr, 5 * sizeof(int));
    if (arr == NULL) {
        printf("Reallocation failed.\n");
        return 1;
    }

    arr[3] = 4;
    arr[4] = 5;

    printf("Resized array: ");
    for (i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }

    free(arr);
    return 0;
}
  

Try It Now

⚠️ Don’t Forget to Free Memory

Whenever you use malloc(), calloc(), or realloc(), remember to use free() after you’re done. It avoids memory leaks.

πŸ“Œ Summary

  • malloc(size) β†’ allocates raw memory
  • calloc(n, size) β†’ allocates and initializes memory to 0
  • realloc(ptr, newSize) β†’ resizes memory block
  • free(ptr) β†’ releases memory

🎯 Try This!

Create a program that dynamically allocates memory for a list of names using char**. Resize the list as needed using realloc()!