What is C Struct vs Union Memory- Best C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

PREV_LEC | NEXT_LEC

C Struct vs Union Memory

Padding, offsets and real RAM savings, measured instead of guessed

Comparing C struct vs union memory is the quickest way to understand why unions exist. A structure gives every member its own space, while a union makes all members share one block, and the difference shows up directly in sizeof and in member offsets. In this lecture of our free embedded C course you will measure both with a short program, see padding appear as unused bytes in a diagram, and learn why a union does not always save as much RAM as you hope. This knowledge matters in embedded C programming, where every byte of SRAM counts.

What You Will Learn

  • How struct and union memory differ, with offsets measured by offsetof
  • Where padding comes from and how alignment affects size
  • How to calculate the real RAM saving of a union, including the tag
  • Why a union holding a 5-byte array can still be 8 bytes
  • Practical rules for ordering members to waste fewer bytes

Prerequisites

The two previous lectures on defining and accessing a C union, and the earlier chapter section on structure padding and sizeof.

Measuring C Struct vs Union Memory With sizeof and offsetof

This experiment makes C struct vs union memory visible. We define a structure and a union with the same three members: a flag byte, a 16-bit length and a 32-bit checksum. Then we print their sizes and the offset of each member.

#include <stdio.h>
#include <stddef.h>
#include <stdint.h>

struct frame_s { uint8_t flag; uint16_t len; uint32_t crc; };
union  frame_u { uint8_t flag; uint16_t len; uint32_t crc; };

int main(void)
{
    printf("sizeof struct = %zu\n", sizeof(struct frame_s));
    printf("sizeof union  = %zu\n", sizeof(union frame_u));
    printf("struct offsets: flag=%zu len=%zu crc=%zu\n",
           offsetof(struct frame_s, flag),
           offsetof(struct frame_s, len),
           offsetof(struct frame_s, crc));
    printf("union  offsets: flag=%zu len=%zu crc=%zu\n",
           offsetof(union frame_u, flag),
           offsetof(union frame_u, len),
           offsetof(union frame_u, crc));
    return 0;
}

Build and run

gcc -Wall -Wextra -o cmp cmp.c
./cmp

Expected output (typical for GCC on x86-64 or Arm):

sizeof struct = 8
sizeof union  = 4
struct offsets: flag=0 len=2 crc=4
union  offsets: flag=0 len=0 crc=0

The C struct vs union memory difference is already clear. The three members add up to 7 bytes, yet the struct is 8. The union is only 4, the size of its widest member. In the union, every offset is 0, which proves that all members begin at the same address.

Memory Layout Diagram: C Struct vs Union Memory

struct frame_s: 8 bytes, each member has its own place
Byte01234567
Ownerflagpadlenlencrccrccrccrc
union frame_u: 4 bytes, members overlap
Byte0123
flagflag
lenlenlen
crccrccrccrccrc

In the struct, the 16-bit len must start on an even address, so one padding byte sits after flag. The 32-bit crc then lands at offset 4, which is a multiple of 4. This is alignment, and it is why a struct is often larger than the sum of its members.

C Struct vs Union Memory: Side-by-Side Comparison

Propertystructunion
Member storageEach member has its own bytesAll members share the same bytes
Member offsetsIncreasing, with padding gapsAll zero
SizeSum of members plus paddingLargest member plus alignment padding
Values held at onceAll membersOne member
Typical purposeGroup related dataAlternatives, or several views of the same bytes
Writing one memberLeaves others untouchedOverwrites the others

Alignment Can Make a Union Larger Than You Expect

A union is never smaller than its biggest member, but alignment may push it higher. If one member is a 5-byte array and another is a 32-bit integer, the array alone needs 5 bytes. The integer demands 4-byte alignment, and consecutive array elements of the union must each start aligned, so the compiler rounds 5 up to 8.

union { char buf[5]; uint32_t w; } is 8 bytes
Byte01234567
bufb0b1b2b3b4padpadpad
wwwww

Calculating the Real RAM Saving

A C struct vs union memory comparison is most useful when it ends in a RAM budget. Suppose firmware keeps 100 messages in a queue. Each message can be a command byte, a temperature, a tick count or a 16-character name. Compare three designs:

#include <stdio.h>
#include <stdint.h>

struct all_fields {
    uint8_t  cmd;
    uint16_t temp_dc;
    uint32_t ticks;
    char     name[16];
};

union payload {
    uint8_t  cmd;
    uint16_t temp_dc;
    uint32_t ticks;
    char     name[16];
};

struct tagged_msg {
    uint8_t       kind;
    union payload u;
};

int main(void)
{
    printf("all_fields struct : %zu bytes\n", sizeof(struct all_fields));
    printf("payload union     : %zu bytes\n", sizeof(union payload));
    printf("tagged_msg        : %zu bytes\n", sizeof(struct tagged_msg));
    printf("x100 messages     : %zu vs %zu bytes\n",
           100 * sizeof(struct all_fields), 100 * sizeof(struct tagged_msg));

    union { char buf[5]; uint32_t w; } odd;
    printf("union {char[5]; u32}: %zu bytes\n", sizeof odd);
    return 0;
}
gcc -Wall -Wextra -o save save.c
./save

Expected output:

all_fields struct : 24 bytes
payload union     : 16 bytes
tagged_msg        : 20 bytes
x100 messages     : 2400 vs 2000 bytes
union {char[5]; u32}: 8 bytes
DesignBytes per messagex100
Struct holding every field242400
Payload union only161600
Tagged message (kind + union)202000

The union alone saves 8 bytes per message, but a message needs a kind tag, and the tag drags in 3 bytes of padding to keep the 4-byte-aligned union happy. The real saving is 4 bytes per message, 400 bytes across the queue. That is still valuable on a 4 KB device, but it is not the dramatic number a naive calculation suggests.

Tip

The more different in size your alternatives are, the more a union saves. If all alternatives are about the same size, a union buys you very little.

Reducing Padding in Structures

  • Order members from the largest alignment to the smallest.
  • Group small members (bytes and shorts) together at the end.
  • Print sizeof and offsetof in a unit test so a surprise change breaks the build, not the product.
  • Use _Static_assert(sizeof(struct x) == 12, "layout changed"); for layouts that hardware depends on.

Common Mistakes With C Struct vs Union Memory

  1. Adding up member sizes by hand. Padding makes the answer wrong; call sizeof.
  2. Forgetting the tag when counting union savings. The tag and its padding are part of the cost.
  3. Sending a struct over a wire as raw bytes. Padding and byte order differ between systems.
  4. Packing everything. Packed structs can cause unaligned accesses that are slow or fault on some cores.
  5. Assuming sizes are the same on a PC and a microcontroller. Alignment rules are per target.

Best Practices and Performance Notes

  • Memory is not the only cost: unaligned or padded layouts change access speed and cache or bus behavior.
  • Measure with sizeof and offsetof on the real toolchain for your board.
  • Keep hot data compact and aligned; keep rarely used alternatives in a union.
  • Document why any attribute such as packed is used.

Key Takeaways

  • In C struct vs union memory, struct members have separate storage; union members overlap at offset 0.
  • Struct size includes padding; union size is the largest member rounded for alignment.
  • A tag field and its padding reduce union savings.
  • Always measure with sizeof and offsetof.

Conclusion

Understanding C struct vs union memory turns guesses into numbers. You have seen padding as unused bytes, offsets that prove overlap, and a worked saving that included the cost of a tag. In the final lecture of this chapter we combine the two types: a union inside a struct, a struct inside a union, the tagged union pattern, and then test your knowledge with a quiz and interview questions.

Frequently Asked Questions

What is the difference between struct and union memory in C?

A struct allocates separate storage for each member, so its size is roughly the sum of the members plus padding. A union overlays all members at offset zero, so its size is that of the largest member plus alignment padding.

How do I check member offsets in a struct or union?

Use the offsetof macro from stddef.h. For every member of a union it returns 0; for a struct it returns increasing offsets that include padding.

Why is my struct bigger than the sum of its members?

The compiler inserts padding bytes so each member sits at an address that suits its type. Reordering members from largest to smallest alignment often reduces the padding.

Does a union always save memory compared with a struct?

Not always. The union saves the difference between the sum of members and the largest member, but a tag field and alignment padding can take some of that back. Measure with sizeof for your own types.

Can I use the packed attribute to shrink a struct?

Compilers offer packed attributes, but they can create unaligned accesses that are slow or fault on some CPUs. Reorder members first and use packing only when a hardware or protocol layout demands it.

Is the address of every union member the same?

Yes. Every member starts at the beginning of the union, so a pointer to the union and a pointer to any member compare equal after casting to void pointer.

Free C Tutorial: Final Lecture Ahead

Next: nested structures and unions, the tagged-union pattern, a quiz and interview questions for embedded C programming.

PREV_LEC | NEXT_LEC

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →