TalentJR

⚙️ C programming basics · Class 10 · Lesson 7 of 18 · Free

Dynamic Memory Allocation in C – malloc, calloc, realloc and free

⏱ About 40 minutes · ▶ run real C here — nothing to install · no sign-in

In this lesson you will

  • Ask for memory at run time with malloc and calloc, check for NULL and release it with free
  • Grow an array safely with realloc
  • Explain memory leaks and dangling pointers and avoid them

A school bus app does not know how many students will board today: 12 or 52. A fixed array of 50 either wastes space or overflows. With dynamic memory, your program asks for exactly as much memory as it needs while it runs, and gives it back when done.

What is malloc in C and why do we need it?

Normal local variables live on the stack. Their size is fixed when you write the code, and they vanish when the function ends. The heap is a big pool of memory your program can borrow from while it runs.

malloc(bytes) borrows that many bytes from the heap and returns a pointer to them. For n ints, ask for n * sizeof(int). If there is no memory left, malloc returns NULL, so always check.

When you are done, free(pointer) gives the memory back. malloc and free live in <stdlib.h>.

Try it: change the inputs to 4 students with marks of your choice.

⚙️ C — you can edit this code
Output
How many students? 3
Marks of student 1: 78
Marks of student 2: 91
Marks of student 3: 66
Average of 3 students: 78.33

💡 marks[i] works on heap memory exactly like on an array, because of pointer arithmetic (Lesson 2).

What is the difference between malloc and calloc in C?

malloc does NOT clear the memory. It may hold leftover values, so you must fill it before reading it.

calloc(count, size) gives memory for count items and sets every byte to 0. That is perfect for counters, like tallying votes for class monitor.

Try it: add more votes to the votes array and run again.

⚙️ C — you can edit this code
Output
Riya   votes: 1
Aman   votes: 1
Zoya   votes: 4
Kabir  votes: 2

💡 Each vote is a candidate number: 0 = Riya, 1 = Aman, 2 = Zoya, 3 = Kabir.

How do you grow an array with realloc in C?

Sometimes you do not even know the count in advance, for example scores typed until the user enters 0. realloc(pointer, new_bytes) resizes a heap block and keeps the old values.

realloc may move the block to a new place and return a new pointer. If it fails, it returns NULL but the old block is still yours. So save the result in a temporary pointer first.

Doubling the capacity each time keeps the number of realloc calls small.

Try it: add more scores before the 0 in the inputs and watch the capacity grow.

⚙️ C — you can edit this code
Output
Enter over scores (0 to stop): 6 12 4 9 15 0
[grew to 4] [grew to 8] 
5 overs, 46 runs

How do you create structs and strings on the heap in C?

malloc(sizeof(Student)) gives space for one struct. A function can create it, fill it and return the pointer. The record lives until someone frees it, even after the function ends.

For a string, ask for strlen(text) + 1 bytes: the + 1 is for the '\0' (Lesson 3). Then copy with strcpy.

A struct that owns heap memory needs a matching function to free it, inner parts first.

Try it: create a third student and free it too.

⚙️ C — you can edit this code
Output
Ananya Iyer: 93 (name uses 12 bytes)
Dev: 71 (name uses 4 bytes)

What is a memory leak and a dangling pointer in C?

A memory leak happens when you lose the last pointer to heap memory without freeing it. The memory stays booked until the program ends. A long-running program that leaks, like a server, slowly eats all memory.

A dangling pointer still holds the address of memory that was already freed. Reading or writing through it is undefined behaviour: it may print old values, wrong values, or crash. Freeing the same pointer twice is also a serious bug.

A simple habit helps: right after free(p), write p = NULL. Then a check like if (p != NULL) protects you, and free(NULL) is allowed and does nothing.

Try it: call release(&list) twice. It is safe, because the second call sees NULL.

⚙️ C — you can edit this code
Output
Last item: 50
Memory given back; list is now NULL

💡 int **p is a pointer to a pointer: release needs it to set the caller's list to NULL.

🤔 Predict the output

Think like C: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

int *p = calloc(5, sizeof(int));
int sum = 0;
for (int i = 0; i < 5; i++) {
    sum += p[i];
}
printf("%d\n", sum);
free(p);

Question 2. On this compiler (4-byte pointers), what does this print?

int *p = malloc(10 * sizeof(int));
printf("%zu\n", sizeof(p));
free(p);

Question 3. What does this print?

int *p = malloc(2 * sizeof(int));
p[0] = 5;
p[1] = 6;
int *q = realloc(p, 3 * sizeof(int));
if (q != NULL) {
    p = q;
}
p[2] = 7;
printf("%d\n", p[0] + p[1] + p[2]);
free(p);

🧩 Your challenge

Read the number of days, then that many daily expenses (in Rs) into a malloc'd array. Print the average and every day that was above average. Free the memory. For inputs 5, then 120 80 200 50 150 the output ends with: Average: Rs 120.00 Day 3: Rs 200 Day 5: Rs 150

Expected output (with the inputs given):
How many days? 5
Expenses: 120 80 200 50 150
Average: Rs 120.00
Day 3: Rs 200
Day 5: Rs 150
⚙️ C — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

int marks = malloc(5 * sizeof(int));
printf("done\n");

Line 1: error: incompatible pointer to integer conversion initializing 'int' with an expression of type 'void *' [-Wint-conversion]

✅ Right

int *marks = malloc(5 * sizeof(int));
if (marks != NULL) {
    printf("done\n");
    free(marks);
}

malloc returns an address, so it must go into a pointer (int *), not an int. Check for NULL and free it when done.

❌ Wrong

int n = 5;
int *p = calloc(n, sizeof(int));
int length = sizeof(p) / sizeof(p[0]);
printf("%d items\n", length);
free(p);

Compiles and runs, but prints: 1 items ⏎

✅ Right

int n = 5;
int *p = calloc(n, sizeof(int));
int length = n;
printf("%d items\n", length);
free(p);

sizeof(p) is the size of the pointer, not of the heap block. Keep the count in your own variable.

❌ Wrong

int *p = malloc(3 * sizeof(int));
p = {10, 20, 30};
printf("%d\n", p[0]);
free(p);

Line 2: error: expected expression

✅ Right

int *p = malloc(3 * sizeof(int));
if (p != NULL) {
    p[0] = 10;
    p[1] = 20;
    p[2] = 30;
    printf("%d\n", p[0]);
    free(p);
}

The { } list only works when you declare an array. Heap memory must be filled one item at a time (or in a loop).

📌 Remember

  • malloc(bytes) borrows heap memory at run time; ask for n * sizeof(type).
  • Always check for NULL, and free every block exactly once when you are done.
  • calloc(count, size) also sets the memory to 0; malloc leaves old values.
  • realloc resizes a block and keeps the values; store its result in a temporary pointer first.
  • After free(p), set p = NULL to avoid dangling pointers; lost pointers cause memory leaks.

Finished the quiz and the challenge?

Questions students ask

What is the difference between stack and heap memory in C?

Stack memory holds local variables; it is fast, fixed in size and freed automatically when a function returns. Heap memory is borrowed with malloc, can be any size you choose while running, and stays until you call free.

Do I need to cast malloc in C?

No. In C, the void * that malloc returns converts to any object pointer by itself, so int *p = malloc(...) is fine. You must cast in C++, which is why some books write (int *) malloc(...).

What happens if I forget to free memory in C?

The memory stays booked until the program ends, then the operating system takes it back. In a short program that is harmless, but in programs that run for days it can use up all memory. Free what you malloc.

What does malloc return when it fails?

It returns NULL. This can happen when you ask for a huge amount or the system is out of memory. Using the result without checking would make the program crash or misbehave.