🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Dynamic Memory Allocation in C
Chapter 8 · Pointers · Ask for memory at run time with malloc(), then test yourself with a quiz and interview questions
Topics covered in this free C tutorial
This part of our free C programming course introduces dynamic memory allocation in C: asking the system for memory while the program is running, instead of fixing every size at compile time. You will learn why static arrays are sometimes the wrong tool, where the heap fits among the memory regions, and how malloc() hands you a block through a pointer. As this free C tutorial is also aimed at C programming for embedded systems, we finish with the risks of the heap on small devices, a chapter quiz, programming challenges and a set of interview questions covering this whole block of lectures.
What You Will Learn
- The difference between static and dynamic memory allocation in C
- Where the heap sits compared with the stack and static data
- The prototype of
malloc(), whatsize_treally is, and what comes back - The correct idiom for allocating an array, and why you should not cast the result in C
- How to check for failure and why embedded programs must
- Why many embedded projects avoid the heap, and what they use instead
- A quiz and interview questions on arrays of pointers, void pointers and malloc
Prerequisites
Before you start
You should have finished the previous lectures of this chapter, especially the one on the void pointer in C, because malloc() returns a void *. You also need comfortable use of pointers with arrays, sizeof, and basic functions.
Static Versus Dynamic Memory Allocation in C
Everything we have declared so far used static allocation: the size of each array was written into the source code, so the compiler reserved exactly that much memory and it could never grow or shrink. Imagine a serial logger that stores incoming bytes:
uint8_t rx_log[256];
Two problems follow. On a quiet day only 40 bytes arrive, so 216 bytes sit unused and, on a microcontroller with a few kilobytes of RAM, that waste matters. On a busy day 300 bytes arrive and the array is too small, so data is lost or, worse, memory next to the array is overwritten. The program cannot know in advance which day it will get.
Dynamic memory allocation in C solves this by letting the program request a block of the right size at run time, use it through a pointer, and return it when done.
| Property | Static allocation | Dynamic allocation |
|---|---|---|
| Size decided | at compile time | at run time |
| Where it lives | stack or static data area | the heap |
| Lifetime | fixed by scope or program | until you release it |
| Can the size change? | no | yes, by requesting another block |
| Access | by name | only through a pointer |
| Failure mode | build error if too big | request can fail at run time |
Where the Heap Lives
A running program divides its memory into regions. The heap is the pool from which dynamic requests are served, and it is managed by the C library’s allocator.
Typical memory regions of a C program
| Region | Holds | Lifetime |
|---|---|---|
| Code (flash on a microcontroller) | machine instructions, constants | whole program |
Static data (.data, .bss) | globals and static variables | whole program |
| Stack | local variables, return addresses | until the function returns |
| Heap | blocks obtained with malloc() | until freed |
On a Linux PC the allocator grows the heap by asking the kernel for more memory. On a bare-metal microcontroller the heap is usually a region defined by the linker script, and an RTOS such as FreeRTOS can provide its own heap implementations. The important point for you as a programmer: the heap is finite and shared, so a request can be refused.
malloc() in C: Prototype and Rules
The function lives in <stdlib.h>. Older books mention alloc.h or malloc.h, but those are non-standard; always include <stdlib.h>.
void *malloc(size_t size);
| Part | Meaning |
|---|---|
size | the number of bytes requested, not the number of elements |
| Return value on success | a pointer to the first byte of the block |
| Return value on failure | NULL |
| Contents of the block | uninitialized; do not assume zeros |
| Alignment | suitable for any standard object type |
Return type void * | the allocator does not know what you will store |
About size_t. Some textbooks say size_t is simply unsigned int. In fact it is an unsigned integer type chosen by the implementation, large enough to hold the size of any object. On 64-bit Linux it is 8 bytes wide, so treating it as unsigned int can silently truncate large values. Print it with %zu.
The recommended way to call malloc()
Because malloc() returns a void *, and a void * converts to any object pointer in C, you do not need a cast. The safest idiom sizes the block from the pointer itself:
int *p = malloc(n * sizeof *p);
| Style | Example | Comment |
|---|---|---|
| Older style with cast | p = (int *)malloc(n * sizeof(int)); | works, but the cast is redundant and repeats the type |
| Recommended in C | p = malloc(n * sizeof *p); | if you change the type of p, the size updates automatically |
C++ does require the cast because it will not convert a void * implicitly. If you compile your C code with a C++ compiler, add it; otherwise leave it out.
A pointer on the stack, a block on the heap
Example: Dynamic Memory Allocation in C With malloc()
The program below chooses how many integers it needs while running. The count comes from the command line, so you can change it without recompiling. It checks for a bad count, checks that malloc() succeeded, fills the block, prints it, and releases it.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
size_t n = 5; /* default element count */
if (argc > 1) {
n = (size_t)strtoull(argv[1], NULL, 10);
}
if (n == 0) {
fprintf(stderr, "count must be at least 1\n");
return 1;
}
int *samples = malloc(n * sizeof *samples);
if (samples == NULL) {
fprintf(stderr, "malloc failed: asked for %zu bytes\n",
n * sizeof *samples);
return 1;
}
printf("got %zu bytes for %zu ints\n", n * sizeof *samples, n);
for (size_t i = 0; i < n; i++) {
samples[i] = (int)(i * i);
}
for (size_t i = 0; i < n; i++) {
printf("%d ", samples[i]);
}
printf("\n");
free(samples); /* covered properly in the next lecture */
return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o malloc_demo ep_malloc_demo.c
Run with the default count of 5:
./malloc_demo
got 20 bytes for 5 ints
0 1 4 9 16
Run asking for 8 integers. Nothing in the source changed, only the request:
./malloc_demo 8
got 32 bytes for 8 ints
0 1 4 9 16 25 36 49
Ask for an absurd amount (a hundred trillion integers) and the allocator refuses. The program reports the failure instead of crashing:
./malloc_demo 100000000000000
malloc failed: asked for 400000000000000 bytes
And an empty request is rejected by our own check:
./malloc_demo 0
count must be at least 1
Study the three lines that matter. malloc(n * sizeof *samples) converts “n integers” into a byte count. The test samples == NULL guards every later access. After that point samples[i] works exactly like an array, because indexing is just pointer arithmetic. The final free(samples) returns the block to the heap; the next lecture covers free, calloc and realloc properly.
Why You Must Check for NULL
A heap is finite. On a PC the system may run low on memory or refuse an unreasonable request, as the run above showed. On a microcontroller with 20 KB of RAM, the heap can be exhausted by a handful of allocations. If you ignore a failed malloc(), the pointer is NULL and the very next write through it is undefined behavior, which on many embedded targets reads or writes address zero, often with strange side effects instead of an immediate crash.
Dynamic Memory Allocation in C for Embedded Systems
On desktop systems dynamic allocation is routine. In embedded work it comes with real costs, and many teams restrict it or forbid it:
- Fragmentation: repeated allocate-and-free cycles can leave the heap full of small gaps, so a large request fails even when the total free space looks sufficient.
- Unpredictable timing: the time to find a block varies, which is a problem for hard real-time code.
- Leaks over long uptime: a device that runs for months turns a tiny leak into a failure.
- Standards: the MISRA C:2012 guidelines include a rule (21.3) that forbids the allocation functions of
<stdlib.h>in safety-related code.
| Strategy | How it works | Typical use |
|---|---|---|
| Static buffers | sizes fixed at build time | safety-critical and small devices |
| Allocate once at startup | malloc during init, never free | drivers that need configurable buffer sizes |
| Memory pools | fixed-size blocks handed out and returned | message queues, network packets |
| RTOS heap schemes | allocator provided by the RTOS | task and queue creation |
Common Mistakes With malloc()
| Mistake | Consequence | Fix |
|---|---|---|
| Not checking the return value | NULL dereference on failure | test against NULL every time |
| Passing the element count instead of bytes | the block is too small, causing a buffer overrun | multiply by sizeof *p |
| Assuming the memory is zero | garbage values | initialize it, or use calloc |
| Forgetting to release the block | memory leak | one free() for each successful malloc() |
Using the block after free() | use-after-free, undefined behavior | set the pointer to NULL after freeing |
Overflow in n * sizeof *p | a small block is allocated for a huge count | validate n before multiplying |
Best Practices, Performance and Security
- Use
p = malloc(n * sizeof *p);. No cast, no repeated type name. - Check the result immediately and handle failure in a defined way: return an error, retry with less, or halt safely.
- Keep ownership clear. Document which function allocates a block and which function must release it.
- Allocation is relatively slow and has variable latency. Never call it inside an interrupt handler or a time-critical loop.
- Reject unreasonable sizes from external input before calling
malloc(). A size that arrives over a network or from a file must be validated, since an attacker-controlled count can cause integer overflow or memory exhaustion. - If the block held secrets such as keys, clear it before releasing it.
Summary and Key Takeaways
Key takeaways
- Static allocation fixes sizes at compile time; dynamic memory allocation in C sizes memory at run time.
- Dynamic blocks come from the heap and are reached only through pointers.
void *malloc(size_t size);takes bytes and returns a pointer orNULL.- The block is uninitialized, and in C the result needs no cast.
- Use
malloc(n * sizeof *p)and always test forNULL. size_tis an implementation-chosen unsigned type, not necessarilyunsigned int.- Embedded projects often avoid the heap because of fragmentation, timing and leaks.
Conclusion
You can now ask for memory exactly when and where you need it, and you know the discipline that goes with it: compute the size in bytes, check the result, and plan the release. Equally important, you know when not to use it, because small devices reward predictable memory over flexible memory in embedded C programming. In the next lecture of this free embedded C course we complete the set with calloc, realloc and free. Before moving on, try the quiz below. It covers this whole block: arrays of pointers, row pointers, void pointers and malloc.
Quick Quiz: Arrays of Pointers, void Pointers and malloc
Answer each question first, then open the answer. Output predictions assume a 64-bit Linux machine and 4-byte ints.
-
What does the declaration
int *p[4];create?- A. A pointer to an array of 4 ints
- B. An array of 4 pointers to int
- C. An array of 4 ints
- D. A pointer to a pointer to int
Show answer
B. The brackets bind before the star, so
pis an array of 4 elements, each of typeint *. -
On a 64-bit Linux machine, what does
sizeof(int *t[6])report for the arrayt?- A. 6
- B. 24
- C. 48
- D. 12
Show answer
C. Six pointers of 8 bytes each give 48 bytes. On a 32-bit Cortex-M it would be 24.
-
Given
int arr[] = {5, 10, 15, 20};andint *pa[4];withpa[i] = &arr[i];for each i, what doesprintf("%d %d", *pa[2] + 1, *(pa[1] + 1));print?- A. 16 15
- B. 15 15
- C. 16 20
- D. 11 15
Show answer
A.
*pa[2]is 15, plus 1 gives 16.pa[1] + 1points atarr[2], whose value is 15. -
With
int grid[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};and a tableint *row[3]holdinggrid[0],grid[1]andgrid[2], what doesprintf("%d %d", row[2][1], *(*(row + 1) + 3));print?- A. 9 7
- B. 10 8
- C. 10 7
- D. 6 12
Show answer
B.
row[2][1]is the second element of the last row, 10.*(*(row + 1) + 3)is the fourth element of the middle row, 8. -
Which initialization of
int *row[3]is valid whenint grid[3][4]exists?- A.
int *row[3] = grid; - B.
int *row[3] = {grid[0], grid[1], grid[2]}; - C.
int *row[3] = &grid; - D.
int *row[3] = *grid;
Show answer
B. Each
grid[i]decays to anint *. The other forms are invalid initializers or have mismatched pointer types. - A.
-
What happens when you compile
void *vp = &x; printf("%d", *vp);?- A. It prints the value of x
- B. Compile error: invalid use of void expression
- C. It prints a garbage value
- D. It crashes at run time
Show answer
B. A
void *has no pointee type, so the compiler cannot dereference it. Cast first:*(int *)vp. -
After
float f = 2.5f; void *vp = &f;, which expression correctly prints 2.5?- A.
printf("%.1f", *vp); - B.
printf("%.1f", *(int *)vp); - C.
printf("%.1f", *(float *)vp); - D.
printf("%.1f", (float)vp);
Show answer
C. The cast must match the real object type. Reading the float as an int breaks aliasing rules, and casting the pointer itself to float converts the address, not the value.
- A.
-
What does
int a[3] = {1,2,3}; void *vq = a; vq = (int *)vq + 1; printf("%d", *(int *)vq);print?- A. 1
- B. 2
- C. 3
- D. It does not compile
Show answer
B. After the cast to
int *, adding 1 advances bysizeof(int), so the pointer now aims ata[1]. -
In GCC with default settings, what does
vp + 1do whenvpis avoid *?- A. Advances by the size of the last type it pointed at
- B. Advances by 1 byte, as a GNU extension that standard C does not allow
- C. Advances by the size of an int
- D. Always fails to compile
Show answer
B. GCC treats
sizeof(void)as 1. With-pedanticit warns, and with-pedantic-errorsit is an error. -
How many bytes does
int *p = malloc(4 * sizeof *p);request ifintis 4 bytes?- A. 4
- B. 8
- C. 16
- D. 32
Show answer
C. Four ints of four bytes each is 16 bytes.
-
What does
malloc()return when it cannot satisfy a request?- A. 0 bytes of memory with a valid pointer
- B. A pointer to the stack
- C.
NULL - D. It terminates the program
Show answer
C. It returns a null pointer, which your code must test before using the result.
-
Which header declares
malloc()?- A.
<alloc.h> - B.
<memory.h> - C.
<stdlib.h> - D.
<stdio.h>
Show answer
C.
<stdlib.h>is the standard header formalloc,calloc,reallocandfree. - A.
Programming Challenges
- Store the addresses of five integer variables in an array of pointers. Walk the array to find and print the largest value, and print which variable it came from.
- Declare a 3 by 4 matrix and a row pointer table for it. Write a function that exchanges two rows by swapping their pointers only, then print the matrix through the table before and after.
- Write
ep_fill(void *base, size_t count, size_t size, const void *value)that sets every element of any array to one value, using a byte pointer andmemcpy. Test it on an int array and a double array. - Read a count from
argv, allocate that many doubles withmalloc, fill elementiwithi * 0.5, print the average, and handle every failure path.
C Programming Interview Questions on Pointers and malloc
1. What is an array of pointers, and how does it differ from a pointer to an array?
int *p[3] is an array holding three pointers to int. int (*p)[3] is one pointer that aims at an entire array of three ints. The parentheses decide which operator binds first.
2. Why is argv an array of pointers?
Each element points at one argument string. Strings differ in length, so a table of pointers, usually ending in a null pointer, is the natural way to describe them.
3. Why sort an array of pointers instead of the data itself?
Swapping pointers is cheap even for large records, the original order stays intact, and it works on data that cannot be moved, such as constants in flash.
4. How does a jagged array differ from a two-dimensional array?
A 2D array is one contiguous block with equal row lengths. A jagged array is a table of pointers to separate rows of different lengths, so you must keep the lengths yourself and cannot assume the rows are contiguous.
5. Can you pass a 2D array to a function that takes int **?
No. A 2D array decays to int (*)[N], which is a different type. Declare the parameter as int (*m)[N], or build a row pointer table and pass that.
6. What is a void pointer, and why can’t you dereference it?
It is a generic pointer that can hold the address of any object. It carries no type or size, so the compiler cannot know how many bytes to read or how to interpret them. You cast it to a real type first.
7. Can you do arithmetic on a void pointer?
Not in standard C, because sizeof(void) is undefined. GCC allows it as an extension that steps one byte. Portable code casts to the real type or to unsigned char * and scales by the element size.
8. Why does memcpy take const void * for its source?
It must accept any object type, which needs void *, and it promises not to modify the source, which const expresses. That also lets callers pass constants without a warning.
9. Do you cast the result of malloc in C?
No. A void * converts implicitly in C, and a redundant cast repeats the type and, in older code, could hide a missing <stdlib.h> include. C++ requires the cast.
10. What does malloc(0) return?
The behavior is implementation-defined. It may return NULL or a unique pointer that must not be dereferenced. Portable code avoids relying on either.
11. What is the difference between malloc and calloc?
malloc takes a byte count and leaves the memory uninitialized. calloc takes an element count and an element size and returns zero-filled memory, and typical implementations fail safely if the multiplication would overflow.
12. Why is dynamic allocation discouraged in safety-critical embedded code?
It can fragment the heap, takes a variable amount of time, can fail at run time, and leaks accumulate over long uptime. Guidelines such as MISRA C:2012 Rule 21.3 prohibit it, and designers use static buffers or fixed-size pools instead.
13. What is the difference between a memory leak and a dangling pointer?
A leak is a block that was allocated but never released, so the memory is lost. A dangling pointer still holds the address of memory that has already been released or gone out of scope, so using it is undefined behavior.
Frequently Asked Questions
What is dynamic memory allocation in C?
It is the process of requesting memory from the heap while the program is running, using functions such as malloc(), and accessing it through a pointer until it is released.
What does malloc() do in C?
It reserves a block of the requested number of bytes from the heap and returns a pointer to its first byte, or NULL if the request cannot be met. The contents are uninitialized.
Why should I check whether malloc() returned NULL?
Because the heap is finite and a request can fail. Using a NULL pointer is undefined behavior, which on embedded targets can cause silent corruption rather than a clear crash.
Should I cast the return value of malloc() in C?
No. In C a void pointer converts to any object pointer automatically. Write p = malloc(n * sizeof *p);. A cast is only required in C++.
Which header file is needed for malloc()?
<stdlib.h>. Headers such as alloc.h and malloc.h are non-standard and should be avoided in portable code.
Is size_t the same as unsigned int?
No. It is an unsigned integer type chosen by the implementation to hold object sizes. On 64-bit Linux it is 8 bytes wide while unsigned int is 4. Print it with %zu.
Should I use malloc() in embedded systems?
Use it carefully. Many projects allocate only during startup or avoid the heap entirely, preferring static buffers or memory pools to avoid fragmentation, unpredictable timing and leaks.
Keep building your embedded C skills
You have finished this block of the free C programming course. Revisit the quiz until every answer feels obvious, then continue with the next part of Chapter 8.

2 Comments