C++FeaturedMemoryProgrammingTutorials

How to Use malloc in C: Syntax, Examples, free() & Common Mistakes

4 Mins read
How to Use malloc in C: Syntax, Examples, free() & Common Mistakes

Allocate and Manage Dynamic Memory Safely in C

When a C program needs memory whose size is determined at runtime, malloc can reserve a block from the heap. That flexibility comes with responsibility: you must calculate the requested size correctly, check for allocation failure, initialize data before reading it, and release the block when it is no longer needed. This guide covers practical malloc syntax, common mistakes, realloc, and ways to find memory errors with Valgrind or AddressSanitizer.

What malloc Does

The C standard library declares malloc in <stdlib.h>. It requests a block of at least the specified number of bytes and returns a pointer to its beginning. The returned storage is suitably aligned for objects with fundamental alignment requirements, but its contents are uninitialized.

void *malloc(size_t size);
  • size is the number of bytes requested.
  • If the request succeeds, the result points to the allocated block.
  • If the request cannot be satisfied, malloc returns NULL.

In C, a void * converts implicitly to a pointer to an object type, so a cast is unnecessary. Include <stdlib.h> and use sizeof to express the amount of storage needed. For a comparison of the two common allocation functions, see malloc vs calloc.

A Basic malloc Example

This example allocates an array of integers based on a runtime value, checks the result, initializes each element, and frees the allocation:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    size_t n = 5;
    int *arr = malloc(n * sizeof *arr);

    if (arr == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }

    for (size_t i = 0; i < n; ++i) {
        arr[i] = (int)(i + 1);
        printf("%d ", arr[i]);
    }
    putchar('\n');

    free(arr);
    return 0;
}

sizeof *arr gives the size of the pointed-to type, so the allocation stays correct if the pointer’s type changes. The multiplication in n * sizeof *arr can overflow for an untrusted or very large n. Validate the count before allocating; for example, ensure n <= SIZE_MAX / sizeof *arr, with <stdint.h> included for SIZE_MAX.

When to Use—and When to Avoid—malloc

Dynamic allocation is useful when the required size or lifetime is not convenient to determine at compile time. Common cases include:

  • Arrays whose element count comes from input or runtime calculations.
  • Nodes in dynamic data structures such as linked lists and trees.
  • Objects that need to remain available beyond the scope of the function that creates them.

Prefer simpler storage when it meets the requirement. A fixed-size local array or a static object may be easier to manage when the size and lifetime are known. In embedded or real-time code, allocation can have variable timing and may contribute to fragmentation, so projects often use preallocated buffers or memory pools instead. The right choice depends on the application’s constraints; heap allocation is not automatically slower or unsuitable.

Common malloc Mistakes and How to Prevent Them

Ignoring a Possible NULL Result

Always handle allocation failure before using the returned pointer. Dereferencing NULL is undefined behavior and commonly crashes the program.

int *values = malloc(100 * sizeof *values);

if (values == NULL) {
    /* Handle the failure: report it, return, or otherwise recover. */
}

Requesting the Wrong Number of Bytes

malloc takes a byte count, not an element count. This allocates only 10 bytes, which is unlikely to hold 10 integers:

int *values = malloc(10);

Use the element count multiplied by the size of one element:

int *values = malloc(10 * sizeof *values);

Reading Uninitialized Memory

The contents of a block from malloc are indeterminate. Assign values before reading them. If zero-initialized storage is what you need, consider calloc; otherwise, initialize each field or element explicitly. Do not assume that newly allocated memory contains zeros.

Leaking Memory or Using It After free

A memory leak occurs when allocated storage is no longer reachable but has not been released. Free each allocation when its ownership ends:

free(values);
values = NULL;

Calling free on a pointer returned by an allocation function releases that block. Calling it on NULL is safe. Calling it twice on the same allocation, passing an invalid pointer, or using the pointer after the block is freed causes undefined behavior. Setting a pointer to NULL can help prevent accidental reuse through that variable, but it does not update other pointers that may refer to the same block.

For strings and byte buffers, also ensure there is enough space for the data and any required null terminator. Related guides cover memcpy in C and string copying.

Resizing an Allocation with realloc

realloc can change the size of a block previously allocated by a compatible allocation function. It may extend the block in place or move it; if it moves, the old block is freed and the returned pointer refers to the resized allocation. Because failure leaves the original block allocated, do not assign the result directly to the only pointer to that block.

size_t new_count = 20;
int *tmp = realloc(values, new_count * sizeof *values);

if (tmp == NULL) {
    /* values still points to the original allocation. */
    /* Handle failure; keep or free values as appropriate. */
} else {
    values = tmp;
}

As with malloc, check for overflow when calculating the new size. A successful growth does not initialize the added bytes; initialize new elements before reading them. Avoid using realloc(ptr, 0) as a portable way to free memory: its behavior has varied across C standards and implementations. Use free(ptr) when you intend to release the block.

Finding Memory Problems with Valgrind and AddressSanitizer

Careful review helps, but memory tools can catch mistakes that are difficult to spot manually. On supported systems, Valgrind Memcheck can report invalid reads and writes, use of uninitialized values, and allocations that remain unreleased when a program exits. A typical command is:

valgrind --leak-check=full ./program

AddressSanitizer (ASan) detects many out-of-bounds accesses, use-after-free errors, and related memory bugs during testing. Compile with debugging information and sanitizer support, for example:

cc -g -fsanitize=address -fno-omit-frame-pointer program.c -o program

Then run the program normally. Availability and exact options depend on the compiler and operating system. These tools complement, rather than replace, correct ownership rules and allocation checks.

Conclusion

malloc is useful when a C program needs storage whose size or lifetime is determined at runtime. Use sizeof for accurate byte counts, guard against overflow, check for NULL, initialize before reading, and make ownership clear so every allocation is released exactly once. Handle realloc through a temporary pointer, and run memory-checking tools during development. These habits make dynamic memory safer and help prevent leaks, invalid accesses, and hard-to-debug failures.

Leave a Reply

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