Skip to content
StudyFame

Dynamic Memory Allocation in C

So far, every array had a fixed size written in the code, like int marks[100]. What if a class has 5 students today and 500 tomorrow? A fixed array either wastes memory or runs out of space.

Dynamic memory allocation lets your program ask for exactly as much memory as it needs while it is running, and give it back when done. This lesson explains the idea, the stack and the heap, and the four functions you'll use: malloc, calloc, realloc and free.

What You Will Learn

  • What static and dynamic memory allocation mean.
  • The difference between stack and heap memory.
  • Why dynamic allocation is needed.
  • The four memory functions in stdlib.h.
  • The basic steps: allocate, check, use, free.

What is Dynamic Memory Allocation in C?

Exam definition: Dynamic memory allocation is the process of allocating memory at run time from the heap using library functions (malloc, calloc, realloc) and releasing it with free. In static allocation, the size is fixed at compile time.

Memory trick: Static allocation is like booking a fixed hall for a wedding months in advance: same size whether 50 or 500 guests come. Dynamic allocation is like adding chairs as guests arrive and returning them after the function. You must return the chairs (free), or the rental shop runs out.

Stack vs Heap Memory

   High addresses
  +------------------+
  |      STACK       |  local variables, function calls
  |        |         |  grows down, freed automatically
  |        v         |
  |                  |
  |        ^         |
  |        |         |
  |       HEAP       |  malloc / calloc / realloc
  +------------------+  you free it yourself
  |  global/static   |
  +------------------+
  |   program code   |
  +------------------+
   Low addresses
PointStack (static/automatic)Heap (dynamic)
When size is decidedCompile timeRun time
Who frees itAutomatically, when the function endsYou, with free()
Size limitSmall (a few MB)Large (most of the RAM)
Can resize?NoYes, with realloc
Accessed byVariable nameA pointer
LifetimeUntil the block endsUntil you free it

Syntax of the Memory Functions

All four are declared in <stdlib.h>.

void *malloc(size_t size);                 /* size bytes, NOT initialized   */
void *calloc(size_t count, size_t size);   /* count*size bytes, set to 0    */
void *realloc(void *ptr, size_t new_size); /* resize an existing block      */
void  free(void *ptr);                     /* give the block back           */
FunctionJobReturns
mallocMemory allocation: one block of given bytesPointer, or NULL if it fails
callocContiguous allocation: n items, all zeroedPointer, or NULL
reallocRe-allocation: grow or shrink a blockNew pointer, or NULL
freeRelease a blockNothing

They return void * (a generic pointer), which C converts automatically to your pointer type.

The four steps every time

1. ALLOCATE   p = malloc(n * sizeof(int));
2. CHECK      if (p == NULL) { handle the error }
3. USE        p[0] = 5;  ...
4. FREE       free(p);  p = NULL;

Example 1: Array Size Chosen by the User

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

int main(void)
{
    int n, i, total = 0;
    int *marks;

    printf("How many students? ");
    scanf("%d", &n);

    marks = malloc(n * sizeof(int));        /* 1. allocate exactly n ints */
    if (marks == NULL)                      /* 2. check */
    {
        printf("Not enough memory\n");
        return 1;
    }

    printf("Enter %d marks: ", n);
    for (i = 0; i < n; i++)                 /* 3. use like an array */
    {
        scanf("%d", &marks[i]);
        total += marks[i];
    }
    printf("Average = %.2f\n", (float) total / n);

    free(marks);                            /* 4. free */
    marks = NULL;
    return 0;
}

Output

How many students? 4
Enter 4 marks: 70 85 60 95
Average = 77.50

Code Explanation

  1. The size n is known only after the user types it, so a fixed array can't be sized correctly. malloc solves this.
  2. n * sizeof(int) asks for exactly enough bytes for n integers. Using sizeof keeps the code correct on any system.
  3. If memory isn't available, malloc returns NULL. We check before using it.
  4. The pointer marks is used exactly like an array: marks[i] means *(marks + i).
  5. free(marks) returns the memory. Setting marks = NULL prevents a dangling pointer.

How Heap Memory Lives Beyond a Function

Local arrays die when their function returns. Heap memory stays alive until you free it, so a function can create memory and hand it to the caller. This was impossible with local arrays (remember: never return a local address).

Example 2: A Function That Creates and Returns an Array

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

int *make_table(int number, int count)      /* returns heap memory */
{
    int *t = malloc(count * sizeof(int));
    int i;
    if (t == NULL)
        return NULL;
    for (i = 0; i < count; i++)
        t[i] = number * (i + 1);
    return t;                               /* safe: heap memory survives */
}

int main(void)
{
    int *table = make_table(7, 5);
    int i;

    if (table == NULL)
        return 1;

    printf("Table of 7:");
    for (i = 0; i < 5; i++)
        printf(" %d", table[i]);
    printf("\n");

    free(table);                            /* caller frees it */
    table = NULL;
    printf("Memory freed\n");
    return 0;
}

Output

Table of 7: 7 14 21 28 35
Memory freed
  • make_table allocates on the heap and returns the pointer. The memory is still valid in main.
  • Rule: whoever ends up owning the pointer must call free once. Here, that's main.

Advantages and Disadvantages of Dynamic Allocation

AdvantagesDisadvantages
Size decided at run time: no wasteYou must remember to free (or memory leaks)
Can grow or shrink with reallocSlower than stack allocation
Memory can outlive the functionBugs: dangling pointers, double free
Large blocks possibleAccessed only through pointers
Needed for linked lists, trees, graphsHeap can become fragmented

Important Points to Remember

  • Dynamic memory comes from the heap at run time.
  • Include <stdlib.h>.
  • malloc (bytes), calloc (zeroed), realloc (resize), free (release).
  • Always use sizeof to compute sizes.
  • Always check for NULL after allocating.
  • Every allocation needs exactly one free; then set the pointer to NULL.

Common Mistakes Beginners Make

MistakeWhat happensFix
malloc(n) for n intsOnly n bytes: overflow when writingmalloc(n * sizeof(int))
Not checking for NULLCrash if memory runs outif (p == NULL)
Forgetting freeMemory leakFree when done
Using memory after freeDangling pointer: random bugsSet p = NULL after free
Forgetting #include <stdlib.h>Warnings, wrong pointer on some systemsInclude it

Dynamic Memory Allocation Practice Questions

  1. What is the difference between static and dynamic memory allocation?
  2. Name the four dynamic memory functions and their header file.
  3. What does malloc return if it fails?
  4. Why can a function return heap memory but not a local array?
  5. Give two disadvantages of dynamic memory allocation.
Show answers
  1. Static: size fixed at compile time, memory managed automatically (stack/global). Dynamic: size decided at run time, memory from the heap, freed by the programmer.
  2. malloc, calloc, realloc, free, in <stdlib.h>.
  3. NULL.
  4. Heap memory lives until freed; a local array is destroyed when the function returns.
  5. Risk of memory leaks if not freed; dangling pointer/double-free bugs; slower than stack (any two).

Coding Exercise

Allocate memory for n floats (n = 3: prices 99.5, 250.0, 45.25), store the prices, print the total, then free the memory.

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

int main(void)
{
    int n = 3, i;
    float values[] = {99.5f, 250.0f, 45.25f};
    float *price = malloc(n * sizeof(float));
    float total = 0;

    if (price == NULL)
        return 1;
    for (i = 0; i < n; i++)
    {
        price[i] = values[i];
        total += price[i];
    }
    printf("Total = %.2f\n", total);

    free(price);
    price = NULL;
    return 0;
}
Total = 394.75

Quick Quiz: Dynamic Memory Allocation (MCQ)

  1. Dynamic memory is allocated from the:

    A) Stack   B) Heap   C) Register   D) Code segment

  2. Header file for malloc and free:

    A) stdio.h   B) string.h   C) stdlib.h   D) memory.h only

  3. malloc returns a pointer of type:

    A) int *   B) char *   C) void *   D) float *

  4. Memory from malloc is released by:

    A) The compiler   B) free()   C) The end of the function   D) delete

  5. Static memory allocation happens at:

    A) Run time   B) Compile time   C) Link time only   D) Never

Show answers
  1. B: heap.
  2. C: stdlib.h.
  3. C: void *.
  4. B: free().
  5. B: compile time.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

Dynamic allocationMemory at run time from the heap
Header<stdlib.h>
Functionsmalloc, calloc, realloc, free
Return typevoid *; NULL on failure
Stack memoryFreed automatically
Heap memoryFreed by you with free()
StepsAllocate → check → use → free

Frequently asked questions

What is dynamic memory allocation?
Allocating memory at run time from the heap with malloc/calloc/realloc and releasing it with free.
What is the difference between stack and heap?
Stack: automatic, small, fixed sizes. Heap: manual (free), large, sizes chosen at run time.
Why is dynamic memory allocation needed?
When the amount of data is unknown until run time, or memory must outlive a function, or must grow (linked lists, trees).

Remember

  • Dynamic = add chairs as guests arrive, and return them.
  • Every malloc needs one free.

Next Topic

Next lesson: malloc() Function in C. You will study malloc() in detail: its syntax, how it works and how to use it with structures.