Memory alignment
- C course
- Advanced
- Lesson 77/83
- 5 min
Learn memory alignment and struct packing.
Memory alignment
Memory alignment ensures a piece of data sits at an address that is a multiple of a specific value. The CPU reads aligned data in a single instruction; unaligned data needs multiple accesses and is slower.
_Alignof(int) gives the required alignment of a type; on Linux x86-64 it is 4 for int. In a struct, field order affects the total size: in struct { char tag; int value; } 3 bytes of padding are added after tag; offsetof(struct Item, value) returns 4. Ordering fields from largest to smallest reduces padding.
Item struct
You declare struct Item { char tag; int value; }. tag is 1 byte, value is 4-byte aligned. 3 bytes of padding go in between; offsetof(struct Item, value) returns 4.
In this lesson we print the int alignment (4) with _Alignof(int) and the offset of value (4) with offsetof(struct Item, value). Both are 4. The <stddef.h> header provides the offsetof macro. This knowledge is the foundation for understanding struct size and memory layout.
Practice Alignment and offset
Declare struct Item { char tag; int value; };. In main print printf("hizalama: %zu\n", (size_t)_Alignof(int)); and printf("ofset: %zu\n", offsetof(struct Item, value));. Add the <stddef.h> header.
Starter code
#include <stdio.h>
#include <stddef.h>
// Declare Item struct: char tag, int value
// main: print int alignment and value offset
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <stddef.h>
struct Item {
char tag;
int value;
};
int main(void) {
printf("hizalama: %zu\n", (size_t)_Alignof(int));
printf("ofset: %zu\n", offsetof(struct Item, value));
return 0;
}Expected output
hizalama: 4 ofset: 4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match alignment concepts
| Term | Meaning |
|---|---|
_Alignof |
Type alignment |
offsetof |
Field offset |
padding |
Padding byte |
struct |
Field order |
2 What is _Alignof(int) on Linux x86-64?
- 4 Correct answer
- 1
- 2
- 8
Explanation: int is 4-byte aligned; _Alignof returns 4.
3 _Alignof call
printf("hizalama: %zu
", (size_t)_Alignof(____));
printf("hizalama: %zu
", (size_t)_Alignof(int));
Explanation: _Alignof(int) gives the int alignment.