What are Dynamic Memory Allocation in C-Best C Language Course For Beginners

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

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

dynamic memory allocation in C malloc in C free C programming course free C tutorial C programming for embedded systems C interview questions

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(), what size_t really 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.

PropertyStatic allocationDynamic allocation
Size decidedat compile timeat run time
Where it livesstack or static data areathe heap
Lifetimefixed by scope or programuntil you release it
Can the size change?noyes, by requesting another block
Accessby nameonly through a pointer
Failure modebuild error if too bigrequest 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

RegionHoldsLifetime
Code (flash on a microcontroller)machine instructions, constantswhole program
Static data (.data, .bss)globals and static variableswhole program
Stacklocal variables, return addressesuntil the function returns
Heapblocks 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);
PartMeaning
sizethe number of bytes requested, not the number of elements
Return value on successa pointer to the first byte of the block
Return value on failureNULL
Contents of the blockuninitialized; do not assume zeros
Alignmentsuitable 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);
StyleExampleComment
Older style with castp = (int *)malloc(n * sizeof(int));works, but the cast is redundant and repeats the type
Recommended in Cp = 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

samples (pointer variable)
points to
heap block: 5 ints = 20 bytes

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.
StrategyHow it worksTypical use
Static bufferssizes fixed at build timesafety-critical and small devices
Allocate once at startupmalloc during init, never freedrivers that need configurable buffer sizes
Memory poolsfixed-size blocks handed out and returnedmessage queues, network packets
RTOS heap schemesallocator provided by the RTOStask and queue creation

Common Mistakes With malloc()

MistakeConsequenceFix
Not checking the return valueNULL dereference on failuretest against NULL every time
Passing the element count instead of bytesthe block is too small, causing a buffer overrunmultiply by sizeof *p
Assuming the memory is zerogarbage valuesinitialize it, or use calloc
Forgetting to release the blockmemory leakone free() for each successful malloc()
Using the block after free()use-after-free, undefined behaviorset the pointer to NULL after freeing
Overflow in n * sizeof *pa small block is allocated for a huge countvalidate 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 or NULL.
  • The block is uninitialized, and in C the result needs no cast.
  • Use malloc(n * sizeof *p) and always test for NULL.
  • size_t is an implementation-chosen unsigned type, not necessarily unsigned 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.

  1. 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 p is an array of 4 elements, each of type int *.

  2. On a 64-bit Linux machine, what does sizeof(int *t[6]) report for the array t?

    • 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.

  3. Given int arr[] = {5, 10, 15, 20}; and int *pa[4]; with pa[i] = &arr[i]; for each i, what does printf("%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] + 1 points at arr[2], whose value is 15.

  4. With int grid[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}; and a table int *row[3] holding grid[0], grid[1] and grid[2], what does printf("%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.

  5. Which initialization of int *row[3] is valid when int 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 an int *. The other forms are invalid initializers or have mismatched pointer types.

  6. 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.

  7. 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.

  8. 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 by sizeof(int), so the pointer now aims at a[1].

  9. In GCC with default settings, what does vp + 1 do when vp is a void *?

    • 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 -pedantic it warns, and with -pedantic-errors it is an error.

  10. How many bytes does int *p = malloc(4 * sizeof *p); request if int is 4 bytes?

    • A. 4
    • B. 8
    • C. 16
    • D. 32
    Show answer

    C. Four ints of four bytes each is 16 bytes.

  11. 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.

  12. 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 for malloc, calloc, realloc and free.

Programming Challenges

  1. 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.
  2. 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.
  3. 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 and memcpy. Test it on an int array and a double array.
  4. Read a count from argv, allocate that many doubles with malloc, fill element i with i * 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.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →