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.sizeof(array) returns the size of the entire array, not the size of a pointer.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)
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
Story
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
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.