Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Understanding Memory Layout of Structs | Section
C Structs

bookUnderstanding Memory Layout of Structs

メニューを表示するにはスワイプしてください

Memory structures in the C programming language play a key role in understanding how data is stored and accessed in memory. When a structure is defined in C, the compiler determines how to place its members in memory based on alignment and padding rules.

Here's an overview of how basic memory allocation for structures works in C:

main.c

main.c

copy
123456789101112131415
#include <stdio.h> // simple struct struct Test { char x; // 1 byte int y; // 4 bytes }; int main() { struct Test example; printf("Size of struct Test: %zu\n", sizeof(example)); printf("Address of example.x (char): %p\n", &example.x); printf("Address of example.y (int): %p\n", &example.y); return 0; }

As expected, such a structure should occupy 5 bytes: 1 byte for char x, 4 bytes for int y, but this will be 8 bytes.

Why is the size of the structure much larger than we expected?

This occurs because the compiler can insert padding between members to ensure that each member begins at an address that is a multiple of its size.

In the image, you can see that the first part of memory (lighter section) belongs to the variable char x, which takes up just one byte. After that, there are three empty bytes — this is padding, automatically added by the compiler to ensure that the next element starts at the correct address. Following the padding, the variable int y is stored, which occupies four bytes.

As a result, the structure takes up a total of eight bytes: one for char, three for alignment, and four for int.

This layout exists to help the processor access data more efficiently. Without alignment, accessing structure members would take more time, and the program would run slower.

question mark

Why does sizeof(struct Test) return 8 instead of 5?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  10

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  10
some-alt