Menu

Your Struct is Wasting Memory and You Don't Know It
📰
0

Your Struct is Wasting Memory and You Don't Know It

DEV Community·Dharrsan Amarnath·about 1 month ago
#AWLGM4lt
Reading 0:00
15s threshold

We write structs by listing fields in whatever order feels readable. Name, then age, then score. It compiles. It runs. The compiler silently bloats it, misaligns it, or both, and you ship it without ever checking. Here are three structs holding the exact same six fields: #include <stdio.h> #include <stdint.h> #include <stddef.h> struct Good { double balance ; uint64_t transaction_id ; int32_t account_type ; int16_t region_code ; char status ; char currency [ 4 ]; }; struct Bad { char status ; double balance ; int16_t region_code ; uint64_t transaction_id ; char currency [ 4 ]; int32_t account_type ; }; struct __attribute__ (( packed )) PackedBad { char status ; double balance ; int16_t region_code ; uint64_t transaction_id ; char currency [ 4 ]; int32_t account_type ; }; int main () { printf ( "Good: %zu bytes \n " , sizeof ( struct Good )); printf ( "Bad: %zu bytes \n " , sizeof ( struct Bad )); printf ( "PackedBad: %zu bytes \n " , sizeof ( struct PackedBad )); return 0 ; } Enter…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More