ProgrammingBackend C Developer

How does the sizeof operator work in C, and what pitfalls exist when using it?

Pass interviews with Hintsage AI assistant

Answer

The sizeof operator is used to determine the size of a type or object in bytes at compile time. It is often needed for memory allocation, calculating the sizes of structures and arrays.

Example:

int a; printf("%zu\n", sizeof(a)); // size of variable a of type int printf("%zu\n", sizeof(int)); // size of type int

Features:

  • sizeof returns size_t, which is always >= 0.
  • For arrays, sizeof(array) returns the size of the entire array, not the size of a pointer.
  • When passing an array to a function, you lose information about its size.

Example of a pitfall:

void foo(int arr[]) { printf("%zu\n", sizeof(arr)); // will print the size of the pointer, not the array! } int arr[10]; foo(arr); // sizeof(arr) == 40 (usually), sizeof(arr in foo) == 8 (usually)

Trick question

What will the expression sizeof('a') return in C?

Answer: Although 'a' looks like a char, the expression sizeof('a') results in the size of type int, as a character constant in C is of type int.

Example:

sizeof('a') // usually 4, not 1

Examples of real errors due to ignorance of the nuances of the topic


Story

In the project, memory was allocated for copying a string like this: malloc(strlen(str) * sizeof(char)), forgetting about the null character. This led to the loss of the last byte and the emergence of bugs when working with standard library string processing functions.

Story

One of the modules used sizeof(arr) in a function, expecting the size of the entire structure, but only got the size of the pointer. As a result, too little data was written to memory, which caused heap corruption.

Story

A developer decided to use sizeof('a') to allocate memory for one letter, expecting 1 byte, but got 4 (or 8) — this resulted in inefficient memory usage and problems in code dependent on the expected size.