🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C malloc Function Explained
Learn malloc in C step by step: heap vs stack, sizeof, NULL checks and embedded cautions in our free C programming course.
What You Will Learn
- What malloc in C does and where the memory comes from
- How to size a request with sizeof and avoid byte-count mistakes
- Why the NULL check is mandatory, especially in embedded C programming
- How to build, run and debug a complete malloc program
- When dynamic allocation is a bad idea on microcontrollers
Prerequisites
- Pointers, address-of and dereference operators (earlier lectures of this chapter)
- Pointer arithmetic and the equivalence of p[i] and *(p + i)
- A GCC (or compatible) compiler on Linux, macOS or WSL
What Is malloc in C and Why Do We Need It?
Every variable you have declared so far in this free C programming course had a fixed size decided while you were typing the program. An array like int readings[6] always holds six integers, even if today’s sensor only produced three samples, and it can never hold seven. malloc in C removes that limitation: it lets a running program ask the operating system, or on a microcontroller the C library’s heap manager, for a block of memory whose size is known only at run time.
The name is short for memory allocation. The function lives in <stdlib.h>, takes a single argument (the number of bytes you want) and returns the address of the first byte of a fresh block. That address has type void *, which is C’s “pointer to anything” type. Because the block has no variable name, the only way to reach it is through a pointer, so everything you learned in the Pointers chapter about dereferencing, subscripting and pointer arithmetic now becomes essential. If you are following this free C tutorial for embedded C programming, treat this lecture as the bridge between pointers and real, flexible data structures.
Prototype to remember
void *malloc(size_t size); — returns a pointer to size bytes of uninitialised memory, or NULL if the request cannot be satisfied.
Where Does malloc Memory Come From? Stack vs Heap
A C program normally sees three regions of data memory. Static and global variables live in the data and BSS sections for the whole life of the program. Local variables and function arguments live on the stack, which grows and shrinks automatically as functions are called and return. The third region is the heap, a pool of memory that you borrow explicitly and give back explicitly. malloc takes memory from the heap; free (next lectures) returns it.
Stack pointer variable, heap block (illustrative addresses)
Notice what the diagram shows: the pointer variable temps is an ordinary local variable on the stack, only a few bytes in size. The 24-byte block it points to lives somewhere else entirely. When the function returns, the stack variable disappears, but the heap block stays reserved until somebody calls free. Keep this split in your head; almost every dynamic-memory bug is a mismatch between the lifetime of the pointer and the lifetime of the block.
How a malloc call is processed
Life of one malloc request
On a desktop Linux machine the allocator (glibc) may grow the heap with system calls such as brk or mmap. On a bare-metal microcontroller the C library (newlib, for example) usually grows the heap inside a region defined by your linker script, and when that region is full malloc simply fails. Either way, the contract you code against is identical: a pointer on success, NULL on failure.
Using malloc in C: Step-by-Step Example
Here is a complete program written from scratch for this lecture. It reserves room for six temperature readings, fills them, prints them and computes an average. Study the three habits it follows: size the request with sizeof *pointer, check for NULL immediately, and call free exactly once.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
size_t count = 6;
int *temps = malloc(count * sizeof *temps); /* room for 6 readings */
if (temps == NULL) {
fprintf(stderr, "heap exhausted\n");
return 1;
}
printf("requested bytes : %zu\n", count * sizeof *temps);
printf("one element : %zu bytes\n", sizeof *temps);
for (size_t i = 0; i < count; i++)
temps[i] = 20 + (int)i * 3; /* fill before reading */
long sum = 0;
for (size_t i = 0; i < count; i++) {
printf("temps[%zu] = %d\n", i, temps[i]);
sum += temps[i];
}
printf("average = %ld\n", sum / (long)count);
free(temps);
return 0;
}
Build and run it:
gcc -std=c17 -Wall -Wextra -Wpedantic -o ep_malloc_basic ep_malloc_basic.c
./ep_malloc_basic
Expected output:
requested bytes : 24
one element : 4 bytes
temps[0] = 20
temps[1] = 23
temps[2] = 26
temps[3] = 29
temps[4] = 32
temps[5] = 35
average = 27
Reading the program line by line
malloc(count * sizeof *temps)asks for 6 × 4 = 24 bytes on a platform whereintis 4 bytes. The request is written in terms of the pointer’s own target type, so if you later changeinttoint16_tthe size updates itself.if (temps == NULL)protects every later line. Without it, a failed allocation would turn the firsttemps[i] = ...into a write through a null pointer.- The fill loop writes every element before anything reads it. malloc does not clear memory, so the content right after the call is whatever bytes happened to be there.
free(temps)hands the block back. Calling it twice, or touchingtempsafterwards, is undefined behaviour.
The sizeof Rule: Bytes, Not Elements
malloc counts in bytes. Beginners often write malloc(10) intending “ten integers” and receive just ten bytes, enough for two integers and a half on a 32-bit int platform. The program then runs fine in small tests and corrupts the heap in bigger ones. Always multiply the element count by the element size.
| Request | Bytes reserved (int = 4) | Integers that fit | Verdict |
|---|---|---|---|
malloc(10) | 10 | 2 | Bug: counts bytes, not integers |
malloc(5 * sizeof(int)) | 20 | 5 | Correct, but type is repeated |
malloc(5 * sizeof *p) | 20 | 5 | Best: follows the pointer’s type |
malloc(n * sizeof *p) | 4n | n | Best, but check n * size for overflow |
Older textbooks were written for 16-bit compilers where int was two bytes, so a call like malloc(10) happened to fit five integers there. Today an int is four bytes on almost every compiler you will meet, from 32-bit ARM Cortex-M parts to 64-bit PCs. Never hard-code the size; let sizeof answer it.
Always Check the Return Value of malloc
The heap is finite. A desktop may refuse a gigantic request, and a microcontroller with 64 KB of RAM can run dry after a few thousand small allocations. When that happens malloc returns NULL, and your program has to decide what to do: report an error, free something, fall back to a smaller buffer or enter a safe state. What it must never do is carry on as if nothing happened.
int *buf = malloc(n * sizeof *buf);
if (buf == NULL) {
/* log the failure, release what you hold, return an error code */
return -1;
}
Do not hide failures
Calling exit(1) inside a helper is acceptable for a classroom program, but firmware should propagate an error code upward so the caller can recover. A device that resets itself because one allocation failed is a bug report waiting to happen.
Should You Cast the Result of malloc?
In C, a void * converts to any object-pointer type automatically, so int *p = malloc(...) is complete and correct. Many older books show (int *) malloc(...), and you will see that in legacy code. The cast is only required in C++, where the implicit conversion is not allowed. In a pure C course the cast adds noise, and in pre-C99 code it could even hide a missing #include <stdlib.h>. Modern guidance is to leave it out. If your project is compiled as both C and C++, keep the cast and a comment explaining why.
Common malloc Mistakes and Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Segmentation fault right after malloc | Result not checked, pointer is NULL | Test for NULL before first use |
| Random values printed | Reading memory before writing it | Initialise, or use calloc (next lecture) |
| Heap corruption, crash far from the bug | Wrote past the end of the block | Check loop limits; run with -fsanitize=address |
| Compiler warns about implicit declaration | Missing <stdlib.h> | Include it; never use <alloc.h> or <malloc.h> in portable code |
| Program slowly uses all RAM | Blocks never freed | Pair every malloc with one free (see lecture 48) |
Debug tip
Compile test builds with gcc -g -fsanitize=address,undefined. AddressSanitizer reports out-of-bounds writes and use-after-free with the exact source line, which is far faster than guessing.
malloc in Embedded C Programming
Dynamic memory is a hot topic in embedded work, so it deserves honest treatment in any free embedded C course. Allocation time is not fixed, repeated allocate/free cycles can fragment a small heap until a request fails even though enough total bytes are free, and a leak that costs nothing on a PC will eventually halt a device that must run for months. For these reasons coding standards such as MISRA C forbid the standard allocation functions in safety-critical code, and many projects allocate everything once during start-up and never again.
- Prefer static buffers or fixed-size memory pools when the maximum size is known at design time.
- If you do use malloc, do it during initialisation, not inside interrupt handlers or hard real-time loops.
- Know your heap size: look for the heap region or
_sbrkimplementation in your linker script and startup code. - Always handle
NULL; on a small device failure is a realistic event, not a theoretical one.
Best Practices Checklist
- Include
<stdlib.h>and usesize_tfor counts. - Write
p = malloc(n * sizeof *p), not a type name inside sizeof. - Check for
NULLon the very next line. - Initialise memory before reading it.
- Decide who owns each block and who frees it, and write that in a comment.
- Guard against multiplication overflow when n comes from user input or a packet header.
Quick Recap: malloc in C
To use malloc in C correctly, remember the sequence: size the request in bytes with sizeof, call malloc, test for NULL, fill the memory and later release it. Whenever a beginner asks why malloc in C returned garbage, the answer is always the same: the block is uninitialised. If you need zeros, the next lecture’s calloc is the right tool. Applying malloc in C in firmware means checking every result and keeping allocations out of interrupt handlers.
Summary and Key Takeaways
- malloc reserves a number of bytes on the heap and returns a
void *to the first byte. - The block is unnamed, so you reach it only through a pointer;
p[i]and*(p + i)both work. - The contents are uninitialised; the result may be
NULLand must be checked. - In C the cast on the return value is unnecessary; use
sizeof *pto size requests. - Dynamic memory is powerful but must be used with discipline on embedded targets.
Conclusion
You now know what malloc does, where its memory lives, how to size a request correctly and why the return value is never optional. The next lecture introduces calloc, which allocates arrays more safely and gives you zero-filled memory for free. Keep the example above handy: change count, run it under valgrind or AddressSanitizer, and confirm for yourself that a correct program is silent while a buggy one is not. That habit of testing small programs is the quickest route through any free C programming course.
Frequently Asked Questions
What does malloc return in C?
It returns a void pointer to the first byte of the allocated block, or NULL if the allocation fails. The memory is not cleared.
Is the memory from malloc initialised?
No. The bytes contain indeterminate values. Write to every element before reading it, or use calloc to get zeroed memory.
Do I need to cast the result of malloc in C?
No. A void pointer converts implicitly to any object pointer type in C. The cast is required only in C++.
What happens if malloc fails?
It returns NULL. Using that pointer is undefined behaviour, so always test the result and handle the failure.
Which header declares malloc?
. Headers like and are compiler-specific or legacy and should not be used in portable code.
Can I use malloc in embedded C programming?
Yes, on many targets, but with care: allocate during start-up, check every result, watch heap size and fragmentation, and follow your project’s coding standard, which may forbid it.
What does malloc(0) do?
The behaviour is implementation-defined. It may return NULL or a unique pointer that must not be dereferenced. Avoid relying on it.
Continue the Free C Programming Course
Next up: calloc, the zero-initialising cousin of malloc, and how it differs in practice.

2 Comments