Course contentsShow
← C
Lesson 538 of 1,2198. Memory ManagementFree lesson

Calculating size with sizeof

Calculating size with sizeof

What you'll learn: How to use the sizeof operator to determine exactly how many bytes of memory your data types require for allocation.

The problem: Guessing is dangerous

When you ask the computer for memory using functions like malloc, you can’t just say "give me enough room for an integer." The computer speaks in bytes. You might think, "Okay, an integer is 4 bytes," and type that number manually.

However, C is designed to run on everything from tiny microwave controllers to massive supercomputers. On one machine, an integer might be 4 bytes; on another, it might be 8. If you guess wrong, you might ask for too little space, causing your program to crash when it tries to stuff a large value into a tiny box.

The solution: The sizeof ruler

Think of sizeof as a digital ruler. Before you go to the "Memory Store," you use this ruler to measure your data types. You don't need to know the actual number; you just need to tell the compiler which type you are measuring.

The sizeof operator returns the size (in bytes) of a type or a variable. Because it is calculated by the compiler when your program is built, it is incredibly fast and always accurate for the specific machine running your code.

Using sizeof in code

In most cases, you will use sizeof followed by a data type in parentheses. Here is how you measure different types to prepare for memory allocation:

#include <stdio.h>

int main() {
    // Measuring basic types
    size_t intSize = sizeof(int);
    size_t doubleSize = sizeof(double);
    size_t charSize = sizeof(char);

    printf("On this computer:\n");
    printf("An int needs %zu bytes\n", intSize);
    printf("A double needs %zu bytes\n", doubleSize);
    printf("A char needs %zu bytes\n", charSize);

    // Calculating space for an array of 10 integers
    size_t totalSpace = 10 * sizeof(int);
    printf("To store 10 ints, we need %zu bytes\n", totalSpace);

    return 0;
}

Why this matters for allocation

When we begin dynamic memory management, we rarely use hardcoded numbers. Instead of asking for "40 bytes," we ask for 10 * sizeof(int). This makes your code portable. If you move your code to a different computer where integers are larger, sizeof automatically adjusts the calculation, ensuring your program never runs out of "elbow room."

Key takeaway

Always use sizeof(type) to calculate memory requirements rather than hardcoding numbers, ensuring your code works safely on any computer.