What is sizeof with malloc in C: Explanation and Example
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.
#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; }
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
sizeoftells how many bytes a data type or variable needs.- Use
sizeofwithmallocto allocate the right amount of memory. - Always check if
mallocreturnsNULLto avoid errors. - Remember to
freethe allocated memory to prevent memory leaks.