Kit Library / Computer Science / C Programming / Memory Management

⚡ Topic Learning Kit

Dynamic Memory Allocation in C: malloc and free

English 17 leveled MCQs 25 flashcards 9 games Free

Shared by a Veda teacher · Generated with Veda AI

Veda Bites

The whole idea, one bite at a time

Veda Bites are swipeable micro-lessons — each one teaches exactly one idea. The bites below come from this kit — swipe through them in the app.

💡 Key Idea

Memory on Demand: The Heap at Runtime

Your program can ask for memory while running.

Dynamic memory allocation lets a C program request memory at runtime from a region called the heap, instead of fixing array sizes at compile time.

↳ Dynamic allocation trades compile-time certainty for runtime flexibility — and you become responsible for cleanup.

📖 Definition

malloc and free: The Core Pair

Two functions rule the heap.

Every `malloc` should have a matching `free` somewhere in your program.

↳ malloc gives memory; free takes it back — they are a matched pair.

💻 Code Example

Your First malloc and free

Five lines that allocate and release.

↳ Allocate, check, use, free — the four-step malloc pattern.

➗ Formula

Sizing malloc Correctly

Multiply count by element size.

For 10 integers on a typical 4-byte int system: `malloc(10 * sizeof(int))` requests 40 bytes.

↳ Never hardcode byte counts — use sizeof so your code stays portable.

⚠️ Common Mistake

Forgetting to free: The Memory Leak

Lost pointers eat your RAM.

↳ Unfreed memory is not garbage-collected in C — it is lost until the process ends.

⚖️ Comparison

Stack vs Heap Memory

Two places your variables live.

↳ Stack is automatic and fast; heap is manual, larger, and flexible.

⚙️ Process

What malloc Actually Does

Behind the scenes of a malloc call.

↳ malloc returns raw, uninitialized memory — it does not zero it out.

🚫 Warning

malloc Returns Garbage, Not Zeros

Uninitialized memory is a trap.

↳ Always write before you read memory returned by malloc.

⚠️ Common Mistake

Double Free and Dangling Pointers

Freeing twice crashes programs.

↳ One malloc, one free — and null the pointer right after.

✅ Best Practice

Always Check for NULL

malloc can fail — plan for it.

↳ Treat every malloc result as untrusted until you have checked it for NULL.

🌍 Real World

Where malloc Powers Real Software

Linked lists, strings, and more.

↳ Any data structure whose size is unknown at compile time relies on dynamic allocation.

🎯 Exam Tip

Exam-Ready Facts on malloc and free

Score marks with these exact points.

↳ These five facts cover most exam questions on dynamic allocation.

🧠 Memory Trick

Remember the malloc Lifecycle

Allocate, Check, Use, Free.

Think A-C-U-F: Allocate, Check for NULL, Use, Free. Four steps, every time.

↳ A-C-U-F keeps you from the two most common heap bugs.

❓ Did You Know

malloc's Sibling: realloc

Grow a block without losing data.

`realloc(ptr, new_size)` resizes a previously allocated block, copying the old contents if it must move. It is the third member of the malloc family alongside `calloc`.

↳ realloc lets you grow or shrink a heap block while preserving its data.

💡 Use Case

Building a Linked List Node

One malloc per node.

Each node is allocated individually, so the list can grow to any length at runtime.

↳ Dynamic allocation is what makes self-referential structures like linked lists possible.

Smart notes

What you'll study, topic by topic

1

Dynamic Memory Allocation in C: malloc and free

18 min

Dynamic memory allocation lets a C program request memory at runtime from the heap, rather than fixing sizes at compile time. The malloc function reserves a block of bytes and returns a pointer to it, while free returns…

  • Dynamic memory allocation reserves memory at runtime from the heap.
  • `malloc(size)` returns a `void*` to uninitialized memory or `NULL` on failure.
  • `calloc(n, size)` allocates and zero-initializes memory.

Full explanation, worked examples & memory tricks in the app

Leveled MCQ practice

Try the smart MCQs from this kit

All 17 questions, laddered from warm-up to topper-level, each with its answer and the reasoning behind it.

Warm-up · 6 questions

Q1. Which header file must be included to use `malloc` and `free`?

Beginner
A `<math.h>`
B `<stdlib.h>`
C `<string.h>`
D `<stdio.h>`
Show the answer

B · `<stdlib.h>`

`malloc`, `calloc`, `realloc`, and `free` are all declared in the standard header ``.

Q2. What does `malloc` return when it cannot allocate the requested memory?

Beginner
A `NULL`
B A pointer to the stack
C A pointer to zero bytes
D `-1`
Show the answer

A · `NULL`

`malloc` returns `NULL` on failure, which is why every allocation must be checked before use.

Q3. What is the state of the memory returned by a successful `malloc` call?

Beginner
A Filled with the previous program's data
B All bytes set to zero
C Uninitialized, containing garbage values
D Read-only and protected
Show the answer

C · Uninitialized, containing garbage values

`malloc` returns uninitialized memory; only `calloc` zeroes the bytes it allocates.

Q4. Which function allocates memory for `n` items and initializes every byte to zero?

Beginner
A `free`
B `calloc`
C `malloc`
D `realloc`
Show the answer

B · `calloc`

`calloc(n, size)` allocates space for `n` items of `size` bytes each and zero-initializes all of it.

Q5. What does `free(ptr)` do to the data stored in the block?

Beginner
A It erases all bytes to zero
B It overwrites the data with `NULL`
C It copies the data to the stack
D It leaves the data untouched and marks the block reusable
Show the answer

D · It leaves the data untouched and marks the block reusable

`free` only returns the block to the allocator; it does not erase data or change the pointer's value.

Q6. `malloc`, `calloc`, `realloc`, and `free` are declared in the standard header `<stdlib.h>` and manage heap memory at runtime.

Beginner
A True
B False
Show the answer

A · True

`malloc`, `calloc`, `realloc`, and `free` are declared in the standard header `` and manage heap memory at runtime.

Building up · 6 questions

Q7. A student writes `int *arr = (int *)malloc(5);` intending to store five integers. What is the problem?

Intermediate
A Only 5 bytes are allocated instead of 20
B The cast is illegal in C
C `malloc` cannot allocate fewer than 16 bytes
D The pointer type must be `void*`
Show the answer

A · Only 5 bytes are allocated instead of 20

The size must be `5 * sizeof(int)`; allocating only 5 bytes means writing `arr[3]` corrupts memory beyond the block.

Q8. Why is it safer to write `int *temp = realloc(arr, new_size);` before assigning back to `arr`?

Intermediate
A The compiler requires a temporary for `realloc`
B It prevents the block from being moved
C If `realloc` fails, the original `arr` is still valid and can be freed
D `realloc` is faster with a temporary variable
Show the answer

C · If `realloc` fails, the original `arr` is still valid and can be freed

If `realloc` returns `NULL`, the original block remains valid; assigning directly to `arr` would lose that pointer and leak the old block.

Q9. A program allocates memory inside a loop and never calls `free`. What is the consequence?

Intermediate
A The heap shrinks with each iteration, causing a memory leak
B `malloc` starts returning the same block
C The compiler automatically frees it at exit
D The stack overflows immediately
Show the answer

A · The heap shrinks with each iteration, causing a memory leak

Unfreed allocations accumulate on the heap; a long-running program will eventually exhaust RAM and crash.

Q10. Which of these is illegal because `free` only accepts heap pointers from `malloc`, `calloc`, or `realloc`?

Intermediate
A `free(ptr);` followed by `ptr = NULL;`
B `free(&x);` where `x` is a local `int`
C `free(arr);` where `arr` came from `malloc`
D `free(temp);` where `temp` came from `realloc`
Show the answer

B · `free(&x);` where `x` is a local `int`

`free` cannot release stack variables; passing the address of a local variable is undefined behavior.

Q11. After `free(arr);` the pointer `arr` still holds the old address. What is this pointer called?

Intermediate
A A void pointer
B A dangling pointer
C A null pointer
D A wild pointer
Show the answer

B · A dangling pointer

A pointer that still references freed memory is a dangling pointer; using it is undefined behavior.

Q12. Which statement about `calloc` versus `malloc` is correct?

Intermediate
A `malloc` always zeroes memory, `calloc` does not
B `calloc` costs slightly more time because it zeroes every byte
C Both return memory filled with garbage
D `calloc` is faster because it skips initialization
Show the answer

B · `calloc` costs slightly more time because it zeroes every byte

`calloc` zeroes every byte, which takes a little extra time but saves you from garbage values.

Topper level · 5 questions

Q13. A server allocates a buffer per request but never frees it. Over weeks, what happens?

Advanced
A The buffers are moved to the stack
B Heap usage grows until RAM is exhausted and the server crashes
C `malloc` starts returning `NULL` immediately
D The operating system reclaims each buffer automatically
Show the answer

B · Heap usage grows until RAM is exhausted and the server crashes

Heap memory persists until explicitly freed; a long-running server with leaks slowly consumes all RAM.

Q14. Consider this code: ```c int *arr = (int *)malloc(3 * sizeof(int)); free(arr); free(arr); ``` What is the problem?

Advanced
A `malloc` should have been `calloc`
B The second `free` is a double free and corrupts the heap
C The cast should be removed
D The first `free` is unnecessary
Show the answer

B · The second `free` is a double free and corrupts the heap

Calling `free` twice on the same block is a double free, which corrupts the heap and is undefined behavior.

Q15. Which sequence correctly handles a `realloc` that may fail?

Advanced
A `int *t = realloc(arr, n * sizeof(int)); if (t) arr = t;`
B `free(arr); arr = realloc(arr, n * sizeof(int));`
C `arr = realloc(arr, n * sizeof(int));`
D `realloc(arr, n * sizeof(int));` without assignment
Show the answer

A · `int *t = realloc(arr, n * sizeof(int)); if (t) arr = t;`

Assigning to a temporary first preserves the original pointer if `realloc` fails, preventing a leak.

Q16. You need an array of counters that must all start at 0. Which allocation is the better choice?

Advanced
A `calloc`, because it zero-initializes the memory
B `malloc`, because it is always faster
C A stack array, because it is automatically zeroed
D `realloc`, because it resizes on demand
Show the answer

A · `calloc`, because it zero-initializes the memory

`calloc` is preferred when zero-initialized memory is required; `malloc` would leave garbage values that must be overwritten.

Q17. Consider the following code snippet that attempts to allocate memory for an array of integers and then resize it. Identify the potential issue that could arise if the memory allocation fails during the `realloc` call: ```c int *arr = (int *)malloc(5 * sizeof(int)); if (arr == NULL) return 1; // ... use arr ... arr = realloc(arr, 10 * sizeof(int)); // ... use arr ... free(arr); ```

Advanced
A The new size of `arr` will default to zero if `realloc` fails.
B The program will automatically handle the failure and terminate safely.
C The memory allocated for the original `arr` will be freed automatically.
D The original pointer `arr` will be lost if `realloc` fails, leading to a memory leak.
Show the answer

D · The original pointer `arr` will be lost if `realloc` fails, leading to a memory leak.

The correct option is true because if `realloc` fails, it returns `NULL`, and if you assign that `NULL` to `arr`, you lose the reference to the originally allocated memory, causing a memory leak since you can no longer free that memory.

Flashcards

Tap a card to flip it

25 flashcards in this kit — the app reviews them with spaced repetition so the right card returns on the right day.

Learning games

Play your way through this kit

Every game is built from this kit's own content — scores feed your mastery, so playing counts as studying.

🎮

Word Match

Built from this kit's own content

🎮

True False

Built from this kit's own content

🎮

Memory Match

Built from this kit's own content

🎮

Flashcard Battle

Built from this kit's own content

🎮

Speed Quiz

Built from this kit's own content

🎮

Guess Term

Built from this kit's own content

🎮

Sequence Builder

Built from this kit's own content

🎮

Categorization

Built from this kit's own content

🎮

Revision Battle

Built from this kit's own content

Playable in the app

Study it properly — free, in the app

The full Veda Bites deck, complete notes, spaced-repetition flashcards, leveled MCQs, tests and games for this kit — plus Daily Facts and the Arena, every day.