0
0
CConceptBeginner · 3 min read

What is sizeof with malloc in C: Explanation and Example

In C, sizeof is used with malloc to allocate the correct amount of memory for a data type or structure. It tells malloc how many bytes to reserve, ensuring enough space for the variable or array you want to create.
⚙️

How It Works

Think of malloc as asking the computer to reserve a block of memory, like booking seats in a theater. But to know how many seats to book, you need to know the size of each seat. That's where sizeof comes in—it tells you the size of the data type you want to store, like how big each seat is.

When you write malloc(sizeof(int)), you are asking for enough memory to hold one integer. If you want an array of 5 integers, you write malloc(5 * sizeof(int)), which means booking 5 seats of the size of an integer.

This ensures you get the right amount of memory, avoiding errors like reserving too little or too much space.

💻

Example

This example shows how to use sizeof with malloc to allocate memory for an array of integers and then print them.

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

int main() {
    int n = 5;
    int *arr = malloc(n * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    for (int i = 0; i < n; i++) {
        arr[i] = i * 10;
    }

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

    free(arr);
    return 0;
}
Output
arr[0] = 0 arr[1] = 10 arr[2] = 20 arr[3] = 30 arr[4] = 40
🎯

When to Use

Use sizeof with malloc whenever you need to allocate memory dynamically in C. This is common when you don't know the size of data in advance or when working with arrays, structures, or buffers that change size during program execution.

For example, reading user input to decide how many elements to store, or creating linked data structures like lists and trees, requires dynamic memory allocation with malloc and sizeof.

Key Points

  • sizeof tells how many bytes a data type or variable needs.
  • Use sizeof with malloc to allocate the right amount of memory.
  • Always check if malloc returns NULL to avoid errors.
  • Remember to free the allocated memory to prevent memory leaks.

Key Takeaways

Use sizeof with malloc to allocate the exact memory size needed for data types.
Always multiply sizeof by the number of elements when allocating arrays.
Check malloc's return value to ensure memory was allocated successfully.
Free allocated memory after use to avoid memory leaks.