Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What's the difference between sizeof and alignof?
In C, understanding the difference between sizeof and _Alignof operators is crucial for memory layout optimization. The sizeof operator returns the total size of a type in bytes, while _Alignof (introduced in C11) returns the alignment requirement of a type.
Syntax
sizeof(type) _Alignof(type)
Key Differences
The sizeof operator returns the total memory space occupied by a type, including any padding bytes added for alignment. The _Alignof operator returns the alignment boundary requirement − the address where the type should be placed for optimal access.
Example: Basic Data Types
For primitive data types, sizeof and _Alignof often return the same value ?
#include <stdio.h>
#include <stdalign.h>
int main() {
printf("int: sizeof=%zu, _Alignof=%zu
", sizeof(int), _Alignof(int));
printf("double: sizeof=%zu, _Alignof=%zu
", sizeof(double), _Alignof(double));
printf("char: sizeof=%zu, _Alignof=%zu
", sizeof(char), _Alignof(char));
return 0;
}
int: sizeof=4, _Alignof=4 double: sizeof=8, _Alignof=8 char: sizeof=1, _Alignof=1
Example: Structure with Padding
For user-defined structures, the difference becomes apparent due to padding ?
#include <stdio.h>
#include <stdalign.h>
struct MyStruct {
int x; /* 4 bytes */
double y; /* 8 bytes */
char z; /* 1 byte + padding */
};
int main() {
printf("sizeof(struct MyStruct): %zu bytes
", sizeof(struct MyStruct));
printf("_Alignof(struct MyStruct): %zu bytes
", _Alignof(struct MyStruct));
return 0;
}
sizeof(struct MyStruct): 24 bytes _Alignof(struct MyStruct): 8 bytes
How It Works
The structure requires 24 bytes total due to padding, but its alignment requirement is 8 bytes (determined by the largest member, double). This means instances of MyStruct should be placed at addresses divisible by 8 for optimal performance.
Conclusion
The sizeof operator tells you how much memory a type occupies, while _Alignof tells you the alignment boundary requirement. Understanding both is essential for efficient memory management and avoiding performance penalties from misaligned data access.
