CBSE 2026 results are out, Mukul scored a perfect 100/100 in Computer ScienceSee all toppers →

KwickAcademy C++ · 6 min · free

Dynamic Memory Allocation: malloc, calloc, realloc and free

6 min4 KwickClipsFull text belowFree
Next lesson →Kajal Ma'am (MCA), teaching since 2004Remembered in this browser

Dynamic memory allocation gets heap memory while the program runs, using malloc, calloc, realloc and free from stdlib.h.

On screen in this lesson

Two places for memory

Stack: local variables of a function
Heap: memory you ask for while running
Stack memory is freed automatically
Heap memory stays until you free it

Stack vs heap

PointStackHeap
Size decidedat compile timeat run time
Freed bythe systemyou, with free
Spacesmalllarge
Speedfasterslower
Used throughvariable namespointers

The four functions

malloc: get a block of bytes
calloc: get a block filled with zeros
realloc: change the size of a block
free: give the block back

malloc vs calloc

Pointmalloccalloc
Argumentstotal bytescount, size
Starting valuesgarbageall zeros
Speeda bit fastera bit slower
On failurereturns NULLreturns NULL

Rules of realloc

Old values are kept up to the smaller size
The block may move to a new address
On failure it returns NULL; old block stays
Never write p = realloc(p, size) directly

Using free correctly

Free every block from malloc, calloc, realloc
Free each block only once
Set the pointer to NULL after free
Never free stack memory like &x

Quick answers

What is the difference between malloc and calloc?

malloc takes total bytes and leaves garbage; calloc takes count and size and gives zeros.

What is a memory leak?

Heap memory that is never freed and whose address is lost.

KwickClips from this lesson

Short clips, one idea each. Good for revision the night before.

The full lesson, in text

Hello students, welcome to Kwickprep. You are writing a marks program, but you do not know how many students will join. Should the array hold ten, or ten thousand? Today we will learn to ask for memory while the program runs. We will use malloc, calloc, realloc and free, and we will catch a sneaky bug called a memory leak.

A running C program keeps its data in two main areas of RAM. The stack holds the local variables of a function, like int i inside main. The heap is a large pool of memory that you request while the program is running. When a function ends, its stack memory is cleaned up automatically. Heap memory is different, because it stays reserved until you give it back yourself.

Let us compare the two side by side. On the stack, sizes are fixed when the program is compiled, but heap sizes can be decided at run time. The system frees stack memory, while you must free heap memory. The stack is small, and the heap is much larger. Stack memory is faster to get than heap memory. We use stack memory through variable names, but heap memory only through pointers.

Dynamic memory allocation means getting heap memory while the program runs. C gives four functions for it, all in the header file stdlib dot h. Malloc, short for memory allocation, gets a block of bytes. Calloc, short for contiguous allocation, gets a block and fills it with zeros. Realloc changes the size of a block you already have. Free returns the block to the heap.

Here we ask for space for three integers. The sizeof operator gives the size of one int in bytes. Malloc returns the address of the block, and we store it in the pointer p. If no memory is left, malloc returns NULL, so we always check. Now p works like an array, and it prints ninety. Malloc does not clean the block, so the other two places hold garbage, which means leftover random values. At the end, free of p returns the memory.

Calloc takes two arguments, the number of items and the size of one item. Here m is short for marks, with space for three integers. Pause and predict. What does m of two hold before we store anything? It is zero, because calloc fills every byte with zero. So the program prints zero, zero.

Exams often ask the difference between malloc and calloc. Malloc takes one argument, the total bytes, while calloc takes a count and a size. Malloc leaves garbage values, but calloc sets everything to zero. Because calloc does that extra cleaning, it can be a little slower. Both return NULL when memory is not available.

Now two more students join, and our block is too small. Here t is the table of marks, with room for two integers, and t of one stores seven. Realloc asks for room for four integers. The answer goes into a new pointer n first. If n is not NULL, we copy it into t. The old values are kept, so it still prints seven.

Realloc has four rules to remember. It keeps the old values, up to the smaller of the old and new sizes. It may move the block to a new address, so always use the pointer it returns. If it fails, it returns NULL, and your old block is still there. That is why we never write p equals realloc of p, because a NULL would wipe out our only address.

Free is simple, but mistakes with it crash programs. Every block from malloc, calloc or realloc must be freed once. Freeing the same block twice is a serious bug. After free, the pointer still holds the old address, and it is called a dangling pointer, so set it to NULL. Finally, free only heap memory, never the address of a normal local variable.

Now the bug we promised. A memory leak happens when heap memory is never freed, and we lose its address. In this function, m points to space for one hundred integers. The function returns without calling free. The pointer m lives on the stack, so it disappears, but the heap block stays reserved. Nobody can use that block again until the program ends.

One small leak may look harmless, but it adds up. If report is called one thousand times, one thousand blocks are lost. Programs that run for days, like a railway booking server, slowly use up memory and may crash. The compiler gives no error message for a leak, so you must look for it. The fix is to call free before every return, once you finish with the block.

Let us revise what we learned today. Stack memory is automatic, but heap memory is managed by you. Malloc gives a block with garbage values, and calloc gives a block of zeros. Realloc changes the size, so store its result in a separate pointer first. Free every block exactly once, and then set the pointer to NULL. A heap block that is never freed and whose address is lost is a memory leak.

Courses that teach this

CourseUnit
Programming All levels CPointers and Dynamic Memory

Voice-over in this lesson is AI-generated. The script is written and checked by Kajal Ma'am. Boards can revise a syllabus mid-year, so confirm anything you plan around against the official board circular. Keep your passwords, OTPs and ID numbers to yourself — we never ask for them. To reach Kajal Ma'am, use the WhatsApp button; sharing your number there is how we call you back.

Free to watch, no sign-up. Live classes with Kajal Ma'am are the paid course; these lessons stay free either way.

Want a plan that actually fits your board dates?

Ask Kajal Ma'am directly, 20+ years teaching computer science. Free demo class first, no payment.

Talk to Kajal Ma'am on WhatsApp

Or see the Class 12 Computer Science course →

Studying outside India?

We coach CBSE, IGCSE & international students across the globe, one-to-one, in your local time zone.

Visit International →