C malloc() Function

Intermediate
6 min read
Updated: Nov 2026
1 example

What Is malloc() Function?

void *malloc(size_t size) reserves size bytes and returns a pointer to the block, or NULL on failure. The memory is uninitialized. Always write malloc(count * sizeof *ptr) so the size follows the pointer type, and check the result before use.

Remember
#include <stdlib.h>

int *p = malloc(n * sizeof *p);
if (p == NULL) { /* handle failure */ }
/* ... use p[0] .. p[n-1] ... */
free(p);

Cheat Sheet

Keep these facts handy while you work with malloc() Function in C.

TopicDetail
Header<stdlib.h>
Returnsvoid * or NULL
ContentsIndeterminate (not zero)
Size idiomn * sizeof *p

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: calloc() Function.

Example 1 — Allocate five ints and fill with squares

Use the memory like an array, then release it.

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

int main(void) {
    size_t n = 5;
    int *sq = malloc(n * sizeof *sq);
    if (sq == NULL) {
        fprintf(stderr, "out of memory\n");
        return 1;
    }

    for (size_t i = 0; i < n; i++) sq[i] = (int)(i * i);
    for (size_t i = 0; i < n; i++) printf("%d ", sq[i]);
    printf("\n");

    free(sq);
    return 0;
}

How It Works

  1. sizeof *sq stays correct if the pointer type changes.
  2. The NULL check prevents writing through a failed allocation.
  3. The block is released with free.

Edge Cases & Pitfalls

Check these before relying on malloc() Function in real programs.

uninit

Reading before writing

malloc does not clear memory. Use calloc or memset when you need zeros.

mul

Overflow in size

n * size can overflow size_t. Use calloc(n, size) when n is untrusted.

Key Takeaways

  • Check: result may be NULL.
  • Size: n * sizeof *p.
  • Uninitialized: you must set values.

One line: void *malloc(size_t size) reserves size bytes and returns a pointer to the block, or NULL on failure.

Frequently Asked Questions

A pointer to the start of the allocated block, suitably aligned for any type, or NULL if the allocation failed.
No. The contents are indeterminate. Use calloc if you want zero-initialized memory.
Continue with "C calloc() Function" next. Allocate zero-initialized memory for an array of elements. The C Dynamic Memory Allocation hub lists every topic in order.

Next: calloc() Function

Allocate zero-initialized memory for an array of elements.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful