Dynamic Memory Allocation (uwu)

What is Dynamic Memory Allocation?

Dynamic memory allocation lets you allocate memory at runtime (while the program is running), instead of at compile time (like with arrays).

This is useful when you don’t know in advance how much memory you’ll need — like when you're getting user input or working with variable-sized data.

The Key Functions (from <stdlib.h>)

Function

Purpose

malloc()

Allocates a block of memory

calloc()

Allocates and initializes memory to zero

realloc()

Resizes previously allocated memory

free()

Frees memory that was allocated dynamically

  1. malloc()

    int *arr = (int*) malloc(5 * sizeof(int)); 
    • Allocates memory for 5 integers.

    • sizeof(int) is the size (in bytes) of an integer.

    • Returns a pointer to the first element of the block.

    • The memory contains garbage values, so initialize it yourself.

  2. calloc()

    int *arr = (int*) calloc(5, sizeof(int));
    • Sets all values to zero.

    • Allocates space for 5 integers.

    • Safer than malloc() if you need zero-initialization.

  3. realloc()

    arr = (int*) realloc(arr, 10 * sizeof(int));
    • Changes the size of the memory block (e.g., from 5 to 10 ints).

    • Useful for growing arrays dynamically.

  4. free()

    free(arr);
    • Releases the memory you've allocated with malloc, calloc, or realloc.

    • Always free memory when you’re done to avoid memory leaks.

Key Notes

  • Always check if memory allocation succeeded:

    if (arr == NULL) {
         printf("Memory allocation failed!\n");
    }
    
  • Don’t forget to free() what you malloc() — every allocation should have a matching free.

Example Program

#include <stdio.h>

#include <stdlib.h>

int main() {

int n;

printf("Enter number of elements: ");

scanf("%d", &n);

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

if (arr == NULL) {

printf("Memory allocation failed!\n");

return 1;

}

printf("Enter %d numbers:\n", n);

for (int i = 0; i < n; i++) {

scanf("%d", &arr[i]);

}

printf("You entered:\n");

for (int i = 0; i < n; i++) {

printf("%d ", arr[i]);

}

free(arr); // Clean up memory

return 0;

}