sizeof
sizeof is an operator that yields the size in bytes of a type or an expression. The result has type size_t. For most operands it is a compile-time constant.
Detailed Explanation
sizeof(int) is the size of an int. sizeof x is the size of the object x names. Parentheses are required for types and optional for expressions. sizeof *p is the size of the pointed-to object and does not evaluate p except when the type is a VLA. That is why malloc(n * sizeof *p) stays correct when the type of p changes.
sizeof an array is the whole array, in the scope where the array has not decayed. sizeof a pointer is the pointer. sizeof a function parameter declared as an array is the pointer. This is the most common sizeof bug: void f(int a[8]) { size_t n = sizeof a / sizeof a[0]; } is sizeof(int *) / sizeof(int), which is 2 on LP64, not 8.
sizeof a struct includes padding. sizeof a flexible-array struct does not include the payload. sizeof a VLA is evaluated at run time and can be zero. sizeof an expression is not a trip to memory for ordinary types: sizeof i++ does not increment i.
The unit is char. sizeof(char) is 1 by definition. The number of bits in a char is CHAR_BIT, at least 8. On every hosted platform you will use, it is 8.
Do not use sizeof to compute network sizes of padded structs. Do not use it on a pointer and expect the allocation size; the allocator stored that size internally and does not share it portably.
Code Examples
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p = malloc(4 * sizeof *p); /* 4 ints, type follows p */
if (p == NULL) {
return 1;
}
printf("%zu %zu\n", sizeof p, sizeof *p);
/* typical LP64: 8 4 */
free(p);
return 0;
}#include <stdio.h>
int main(void)
{
int a[4];
printf("%zu\n", sizeof a / sizeof a[0]); /* prints: 4 */
return 0;
}Common Gotchas
`sizeof` a function parameter is the pointer size
pass the length in.
`sizeof(struct S)` with a flexible array member is the header only
`sizeof(struct S)` with a flexible array member is the header only
`sizeof i++` does not increment `i` unless `i` is a VLA length expression
`sizeof i++` does not increment `i` unless `i` is a VLA length expression
`sizeof(a)` where `a` is a pointer is 8 (typically), not the `malloc` size
`sizeof(a)` where `a` is a pointer is 8 (typically), not the `malloc` size