0
0
Cprogramming~5 mins

Why dynamic memory is needed

Choose your learning style9 modes available
Introduction

Dynamic memory lets a program get memory while it runs, not just before it starts. This helps when you don't know how much memory you need in advance.

When you need to store a list but don't know how many items it will have.
When you want to create data structures like linked lists or trees that grow or shrink during the program.
When the size of data depends on user input or external files.
When you want to save memory by only using what you need at the moment.
When you want to share memory between different parts of a program flexibly.
Syntax
C
ptr = malloc(size_in_bytes);
// or
ptr = calloc(number_of_elements, size_of_each);
// and later
free(ptr);

malloc reserves a block of memory but does not clear it.

calloc reserves and clears the memory to zero.

Examples
Reserve memory for 5 integers.
C
int *arr = malloc(5 * sizeof(int));
Reserve and clear memory for 20 characters.
C
char *name = calloc(20, sizeof(char));
Release the memory when done to avoid leaks.
C
free(arr);
Sample Program

This program asks the user how many numbers they want to store. It then uses dynamic memory to create an array of that size, fills it with values, prints them, and frees the memory.

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

int main() {
    int n;
    printf("Enter number of elements: ");
    scanf("%d", &n);

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

    for (int i = 0; i < n; i++) {
        arr[i] = i * 10;
    }

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

    free(arr);
    return 0;
}
OutputSuccess
Important Notes

Always check if malloc or calloc returns NULL, which means memory allocation failed.

Remember to free any dynamic memory you allocate to avoid memory leaks.

Dynamic memory is slower than static memory but more flexible.

Summary

Dynamic memory lets programs use memory flexibly during runtime.

Use malloc or calloc to get memory, and free to release it.

This is useful when you don't know data size before the program runs.