#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →

Malloc Syntax in C with Examples

malloc() asks the C runtime for a block of memory on the heap while your program runs. This page shows its exact syntax, five small programs with their output, and the mistakes that lead to crashes and memory leaks.

Malloc Syntax in C with Examples

Malloc Syntax in C with Examples

Syntax

The prototype is in <stdlib.h>:

void *malloc(size_t size);
  • size: the number of bytes you want. Use sizeof so the size is right on every platform.
  • Return value: a void * to the first byte of the block, or NULL if the request cannot be met.
  • The memory is not initialised. It holds whatever bytes were there before.

The usual pattern is:

type *ptr = malloc(count * sizeof *ptr);

Writing sizeof *ptr instead of sizeof(int) means the size stays correct if you later change the pointer's type. In C you do not need to cast the result, because void * converts to any object pointer automatically. (C++ does need the cast, but C++ code normally uses new or containers instead.)

Heap memory lives outside the stack frame of the function that created it, so it survives after the function returns. See memory layout in C for where the heap sits next to the stack and data segment.

Example 1: one integer

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

int main(void) {
    int *p = malloc(sizeof *p);
    if (p == NULL) {
        fprintf(stderr, "Out of memory\n");
        return 1;
    }
    *p = 42;
    printf("Value: %d\n", *p);
    free(p);
    p = NULL;
    return 0;
}

Output:

Value: 42

Setting p to NULL after free is a habit that turns an accidental second use into an obvious crash instead of silent corruption.

Example 2: an array whose size is known only at run time

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

int main(void) {
    int n = 5;                      /* could come from scanf or a file */
    int *arr = malloc(n * sizeof *arr);
    if (arr == NULL) return 1;

    for (int i = 0; i < n; i++)
        arr[i] = (i + 1) * (i + 1);

    for (int i = 0; i < n; i++)
        printf("%d%s", arr[i], i < n - 1 ? " " : "\n");

    free(arr);
    return 0;
}

Output:

1 4 9 16 25

Once allocated, the block is used exactly like a normal array: arr[i] is the same as *(arr + i). The pointer arithmetic guide explains why, and arrays in C covers fixed-size arrays for comparison.

Example 3: copying a string

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

int main(void) {
    const char *src = "hello heap";
    char *copy = malloc(strlen(src) + 1);   /* +1 for the '\0' */
    if (copy == NULL) return 1;

    strcpy(copy, src);
    printf("%s (%zu chars)\n", copy, strlen(copy));

    free(copy);
    return 0;
}

Output:

hello heap (10 chars)

Forgetting the + 1 for the terminating null byte is one of the most common heap overflows in C. More on how C stores text is in strings in C.

Example 4: a struct

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

struct Student {
    int roll;
    float marks;
};

int main(void) {
    struct Student *s = malloc(sizeof *s);
    if (s == NULL) return 1;

    s->roll = 7;
    s->marks = 88.5f;
    printf("Roll %d scored %.1f\n", s->roll, s->marks);

    free(s);
    return 0;
}

Output:

Roll 7 scored 88.5

This is how nodes of a singly linked list are created: one malloc per node, linked through a pointer field.

Example 5: growing an array with realloc

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

int main(void) {
    size_t cap = 2, len = 0;
    int *v = malloc(cap * sizeof *v);
    if (v == NULL) return 1;

    for (int x = 10; x <= 50; x += 10) {
        if (len == cap) {
            cap *= 2;
            int *tmp = realloc(v, cap * sizeof *v);
            if (tmp == NULL) { free(v); return 1; }
            v = tmp;
        }
        v[len++] = x;
    }

    printf("len=%zu cap=%zu:", len, cap);
    for (size_t i = 0; i < len; i++) printf(" %d", v[i]);
    printf("\n");

    free(v);
    return 0;
}

Output:

len=5 cap=8: 10 20 30 40 50

Capacity grows 2 → 4 → 8. Assign the result of realloc to a temporary first: if it fails it returns NULL but leaves the old block alive, and writing v = realloc(v, ...) would lose your only pointer to it.

malloc, calloc, realloc and free

FunctionSignatureWhat it does
mallocvoid *malloc(size_t size)Allocates size bytes, contents indeterminate
callocvoid *calloc(size_t n, size_t size)Allocates n * size bytes, all set to zero
reallocvoid *realloc(void *ptr, size_t size)Resizes a block, may move it; keeps old contents up to the smaller size
freevoid free(void *ptr)Releases a block; free(NULL) does nothing

Use calloc when you need zeroed memory, such as counters. Common implementations of calloc also check n * size for overflow, which a hand-written malloc(n * size) does not.

Common mistakes

  • Not checking for NULL. Dereferencing a failed allocation is undefined behaviour.
  • Wrong size. malloc(n) for n ints gives n bytes, not n ints. sizeof(ptr) is the size of the pointer, not the data.
  • Reading before writing. malloc memory is not zeroed.
  • Memory leak. Losing the last pointer to a block before calling free.
  • Use after free and double free. Both are undefined behaviour and a frequent source of security bugs.
  • Freeing something malloc did not return, such as a stack array or a pointer into the middle of a block.
  • malloc(0). The result is implementation-defined: either NULL or a pointer you must not dereference but should still free.

To catch these, compile with gcc -g -fsanitize=address prog.c (AddressSanitizer) or run the program under valgrind --leak-check=full ./a.out on Linux.

FAQs

Do I need to cast the result of malloc in C?

No. In C, void * converts to any object pointer type automatically, so int *p = malloc(n * sizeof *p); is correct. A cast is required only in C++.

What does malloc return if it fails?

It returns NULL. Always check the pointer before using it.

What happens if I forget to call free?

The block stays reserved until the program ends. In a long-running program, repeated leaks keep increasing memory use.

Reference: ISO/IEC 9899 (C standard), section 7.22.3 "Memory management functions"; cppreference.com pages for malloc, calloc, realloc and free.

Placed Students

Our Clients

Partners

...