🔴 Advanced  ·  Lesson 33

Dynamic Memory (malloc/free)

The problem with fixed sizes

When you write int marks[50];, you are guessing. What if only 3 students show up — you wasted 47 slots. What if 60 arrive — you run out. A fixed array forces you to decide the size before the program knows how much data it will really have.

Dynamic memory solves this: it lets your program ask for exactly the memory it needs, while it runs. This is a gentle introduction to the idea; for the full malloc/calloc/realloc/free reference, see dynamic memory allocation in C.

Stack vs heap

Your program has two main places to store data, and understanding the difference is the key to dynamic memory.

StackHeap
Managed byAutomatic (the compiler)You (malloc/free)
SizeSmall, fixed earlyLarge, flexible
LifetimeUntil the function returnsUntil you free it
SpeedVery fastSlightly slower

Normal variables and fixed arrays live on the stack. Dynamic memory comes from the heap.

Why dynamic memory exists

Dynamic memory gives you two powers the stack cannot:

  • Size decided at run time — ask the user how many items, then allocate exactly that many.
  • Memory that outlives a function — data made inside a function can stay valid after it returns, because the heap does not clear automatically.

Your first dynamic array

Here is the simplest possible example: an array whose size the user chooses.

C Language
#include <stdio.h>
#include <stdlib.h>
int main() {
    int n;
    printf("How many numbers? ");
    scanf("%d", &n);

    int *arr = malloc(n * sizeof(int));   // exactly n ints
    if (arr == NULL) return 1;            // always check

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

    free(arr);                            // give it back
    return 0;
}
Run: How many numbers? 4
Output:
0 1 4 9

No fixed size in the code — n decides it while the program runs. That is the whole point of dynamic memory.

When to use it

  • You do not know the size until the program runs.
  • The data must survive after the function that created it ends.
  • The data is large — the heap has far more room than the stack.
💡 Keep it simple when you can

For a small, known amount of data, a plain array on the stack is easier and faster. Reach for dynamic memory when you genuinely need flexibility.

Common mistakes

  • Forgetting to check malloc for NULL before using the memory.
  • Forgetting to free, so the program slowly leaks memory.
  • Using the memory after freeing it (a dangling pointer).
  • Thinking heap memory clears itself — it does not until you free it.
🏋️ Practice

Modify the example to read n numbers from the user into the dynamic array, then print their sum. Confirm it works for different values of n, and always free at the end.

Summary

  • Fixed arrays force you to guess the size too early.
  • The stack is automatic but small; the heap is large and managed by you.
  • Dynamic memory (from the heap) lets you size data at run time and outlive functions.
  • Use malloc to request, check for NULL, and free when done.
  • See dynamic memory allocation for malloc, calloc, realloc and free in depth.

Frequently Asked Questions

What is dynamic memory in C?
Dynamic memory is memory your program requests while it is running, rather than fixing the amount when you write the code. You ask for it from an area called the heap using malloc, use it, and then return it with free. This lets a program handle any amount of data decided at run time.
What is the difference between stack and heap in C?
The stack holds local variables and function calls automatically, is fast, and is cleaned up when a function returns — but its size is limited and fixed early. The heap is a larger pool you manage yourself with malloc and free, and memory there stays until you release it, which is what makes it suitable for dynamic data.
Why do we need dynamic memory if arrays exist?
A normal array needs its size known when you write the program, so it either wastes space or runs out. Dynamic memory lets you ask for exactly the amount you need once the program knows it — for example after the user says how many items there are — so nothing is wasted or too small.
Where is dynamically allocated memory stored?
It is stored on the heap, a region of memory separate from the stack that your program manages manually. Memory taken from the heap with malloc stays reserved until you give it back with free, even across function calls.
Is dynamic memory slower than a normal array?
Allocating and freeing heap memory has a small cost that a plain stack array does not, so for small, fixed amounts a normal array is simpler and faster. Dynamic memory is worth it when the size is unknown until run time or when the data must outlive the function that created it.
← Back to C Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.