Skip to content
StudyFame

malloc() Function in C

malloc() is the most used memory function in C. Its name means memory allocation. You tell it how many bytes you need, and it gives you a pointer to a fresh block on the heap.

In this lesson you will master malloc: the exact syntax, the sizeof pattern that avoids size bugs, why the memory contains garbage, and how to allocate strings and structures.

What You Will Learn

  • The syntax and return value of malloc.
  • How to calculate the size with sizeof.
  • Whether to cast the result.
  • Why malloc memory starts with garbage.
  • How to allocate a string.
  • How to allocate one or many structures.

What is malloc() in C?

Exam definition: malloc() allocates a single block of the requested number of bytes on the heap and returns a void * pointer to its first byte. The memory is not initialized (it holds garbage). It returns NULL if the memory can't be allocated.

Memory trick: malloc is like renting an empty flat: you get the keys (a pointer) to the exact space you asked for, but the previous tenant's junk is still inside (garbage values). Clean it (initialize) before living there.

Syntax of malloc()

#include <stdlib.h>

void *malloc(size_t size);           /* size in BYTES */

int *p = malloc(5 * sizeof(int));    /* 5 ints */
int *q = malloc(5 * sizeof *q);      /* same, size taken from q's type */
char *s = malloc(20);                /* 20 chars (sizeof(char) is always 1) */
  • The argument is in bytes. Always multiply by sizeof.
  • sizeof *q means "size of what q points to". If you later change q's type, the size updates automatically. Many programmers prefer this style.
  • Casting: in C, void * converts automatically, so (int *) malloc(...) is not needed. Old textbooks (and C++) write the cast; both compile in C.

How malloc() Works

int *p = malloc(4 * sizeof(int));     (int = 4 bytes, so 16 bytes)

 p ----> +------+------+------+------+
         |  ??  |  ??  |  ??  |  ??  |   heap block, 16 bytes
         +------+------+------+------+   values = garbage until you set them
          p[0]   p[1]   p[2]   p[3]
  1. malloc asks the memory manager for a free block of at least the requested size.
  2. It returns the address of the block's first byte (or NULL).
  3. The block stays reserved until you call free(p).

Example 1: malloc, Initialize, Use, Free

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

int main(void)
{
    int n = 5, i;
    int *squares = malloc(n * sizeof *squares);

    if (squares == NULL)
    {
        printf("malloc failed\n");
        return 1;
    }

    for (i = 0; i < n; i++)          /* initialize: malloc gives garbage */
        squares[i] = (i + 1) * (i + 1);

    printf("Squares:");
    for (i = 0; i < n; i++)
        printf(" %d", *(squares + i)); /* pointer notation also works */
    printf("\n");

    printf("Bytes allocated: %zu\n", n * sizeof *squares);

    free(squares);
    squares = NULL;
    return 0;
}

Output

Squares: 1 4 9 16 25
Bytes allocated: 20

Code Explanation

  1. malloc(n * sizeof *squares) requests 5 × 4 = 20 bytes.
  2. The NULL check protects against running out of memory.
  3. The first loop fills every element. Reading before filling would show garbage.
  4. squares[i] and *(squares + i) are the same element.
  5. sizeof(squares) would give 8 (a pointer), not 20. Remember the allocated size yourself.

Example 2: malloc for a String and for Structures

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

struct student
{
    int roll;
    char name[20];
    float cgpa;
};

char *copy_text(const char *src)
{
    char *dst = malloc(strlen(src) + 1);     /* +1 for '\0' */
    if (dst != NULL)
        strcpy(dst, src);
    return dst;
}

int main(void)
{
    char *college = copy_text("National Institute of Technology");
    struct student *one = malloc(sizeof *one);          /* one structure  */
    struct student *batch = malloc(3 * sizeof *batch);  /* array of three */
    int i;

    if (college == NULL || one == NULL || batch == NULL)
        return 1;

    printf("College: %s (%zu chars)\n", college, strlen(college));

    one->roll = 1;
    strcpy(one->name, "Asha");
    one->cgpa = 9.1f;
    printf("One    : %d %s %.1f\n", one->roll, one->name, one->cgpa);

    for (i = 0; i < 3; i++)
    {
        batch[i].roll = 101 + i;
        sprintf(batch[i].name, "Student%d", i + 1);
        batch[i].cgpa = 7.5f + i * 0.5f;
    }
    for (i = 0; i < 3; i++)
        printf("Batch  : %d %s %.1f\n", batch[i].roll, batch[i].name, batch[i].cgpa);

    free(college);
    free(one);
    free(batch);
    return 0;
}

Output

College: National Institute of Technology (32 chars)
One    : 1 Asha 9.1
Batch  : 101 Student1 7.5
Batch  : 102 Student2 8.0
Batch  : 103 Student3 8.5
  • For a string, allocate strlen(src) + 1: the +1 holds '\0'. Forgetting it is one of the most common heap bugs.
  • malloc(sizeof *one) allocates one structure; access members with ->.
  • malloc(3 * sizeof *batch) allocates an array of structures; access with batch[i].member.
  • sprintf works like printf but writes into a string.
  • Each of the three allocations gets its own free.

Important Points to Remember

  • Syntax: ptr = malloc(count * sizeof *ptr);
  • Size is in bytes; always use sizeof.
  • Memory is not initialized: garbage until you set it.
  • Returns NULL on failure; always check.
  • For strings: strlen + 1.
  • The cast (int *) is optional in C.
  • sizeof(ptr) is the pointer size, not the block size.

Common Mistakes Beginners Make

MistakeWhat happensFix
malloc(strlen(s))No room for '\0': overflowmalloc(strlen(s) + 1)
malloc(sizeof(p)) for a structAllocates 8 bytes (pointer size)malloc(sizeof *p)
Reading before writingGarbage valuesInitialize, or use calloc
Writing p[n] for an n-element blockHeap overflowLast valid index is n − 1
Losing the only pointer: p = malloc(...); p = q;Memory leakFree before re-pointing

malloc() Practice Questions

  1. Write a statement to allocate memory for 50 doubles.
  2. What value does newly malloc'd memory hold?
  3. How many bytes should you allocate to copy the string "India"?
  4. Is casting the result of malloc required in C?
  5. Why is sizeof *p often preferred over sizeof(int)?
Show answers
  1. double *d = malloc(50 * sizeof *d);
  2. Garbage (uninitialized).
  3. 6 (5 letters + '\0').
  4. No; void * converts automatically in C (C++ needs it).
  5. It stays correct even if the pointer's type is changed later.

Coding Exercise

Write int *range(int start, int end) that mallocs an array holding all numbers from start to end. Print range(5, 10) and free it.

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

int *range(int start, int end)
{
    int n = end - start + 1, i;
    int *r = malloc(n * sizeof *r);
    if (r == NULL)
        return NULL;
    for (i = 0; i < n; i++)
        r[i] = start + i;
    return r;
}

int main(void)
{
    int *r = range(5, 10);
    int i;

    if (r == NULL)
        return 1;
    for (i = 0; i < 6; i++)
        printf("%d ", r[i]);
    printf("\n");
    free(r);
    return 0;
}
5 6 7 8 9 10

Quick Quiz: malloc() in C (MCQ)

  1. malloc stands for:

    A) Memory allocation   B) Multiple allocation   C) Main allocation   D) Matrix allocation

  2. The argument of malloc is the size in:

    A) Elements   B) Bits   C) Bytes   D) Kilobytes

  3. Memory returned by malloc is:

    A) Set to 0   B) Set to 1   C) Uninitialized   D) Set to NULL

  4. Correct allocation for 10 ints:

    A) malloc(10)   B) malloc(10 * sizeof(int))   C) malloc(int, 10)   D) malloc(sizeof(10))

  5. If malloc fails, it returns:

    A) 0 bytes   B) −1   C) NULL   D) An error message

Show answers
  1. A: memory allocation.
  2. C: bytes.
  3. C: uninitialized.
  4. B.
  5. C: NULL.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

Prototypevoid *malloc(size_t size);
Size unitBytes: count × sizeof
Initial valuesGarbage
On failureReturns NULL
String copy sizestrlen + 1
Cast in COptional
Releasefree(ptr)

Frequently asked questions

What does malloc do?
Allocates a block of the requested bytes on the heap and returns a void pointer to it (or NULL).
Does malloc initialize memory?
No, it contains garbage; use calloc for zeroed memory.
Should you cast malloc's result in C?
Not needed in C (void * converts automatically); it is required in C++.

Remember

  • malloc = empty flat with old junk: clean before use.
  • count × sizeof, then check NULL.

Next Topic

Next lesson: calloc() and malloc vs calloc. You will learn calloc() and the exact differences between malloc and calloc.