01. Unions & Shared Memory Layout in C

🟡 Difficulty: Intermediate | Overlapping Memory Locations, Variant Data Types & Tagged Unions

📖 Definition

A union in C is a user-defined composite type where all member fields share the exact same starting RAM memory location. The size of a union is equal to the size of its single largest member. Writing a value to one union member overwrites the shared memory bits of all other members.

🎯 Why It Is Used

  • Memory Conservation: Representing mutually exclusive variant data (e.g. a packet payload holding an int OR a double OR a char[16] string, but never simultaneously).
  • Tagged Variant Records: Combining a struct with an enum type tag and a union to create type-safe polymorphism in C.
  • Type Punning (Low-Level Bit Inspection): Reinterpreting raw float or integer bit patterns without invoking undefined behavior conversions.

⚙️ How It Works: Struct vs Union Allocation

Feature Structure (struct) Union (union)
Memory Allocation Sequential sum of member sizes (+ padding) Size of single largest member only
Member Addresses Distinct offset address for each member All members share identical base address
Simultaneous Member Storage ✅ All members hold valid values at once ❌ Only ONE active member holds a valid value at a time

📝 Syntax

// 1. Union Declaration
union Value {
    int i_val;       // 4 bytes
    double d_val;    // 8 bytes (LARGEST MEMBER)
    char str_val[16];// 16 bytes (LARGEST MEMBER)
}; // sizeof(union Value) == 16 bytes!

// 2. Accessing Members
union Value v;
v.i_val = 42;             // Activates integer member
v.d_val = 3.14159;        // Overwrites i_val memory! Now d_val is active!

🔀 Tagged Variant Union Pattern

To safely track which member inside a union currently holds valid data, combine an enum discriminator tag with a union inside a wrapping struct:

typedef enum { VAL_INT, VAL_DOUBLE, VAL_STRING } VariantType;

typedef struct {
    VariantType type; // Tag indicating active union member
    union {
        int i_val;
        double d_val;
        char str_val[32];
    } data;
} TaggedVariant;

🌱 Beginner Example: Address Overlap Demonstration

#include <stdio.h>

union Data {
    int i;
    float f;
    char str[20];
};

int main(void) {
    union Data data;

    printf("sizeof(union Data) = %zu bytes\n", sizeof(data));

    data.i = 100;
    printf("data.i address: %p | Value: %d\n", (void*)&data.i, data.i);

    data.f = 220.5f; // Overwrites data.i!
    printf("data.f address: %p | Value: %.1f\n", (void*)&data.f, data.f);
    printf("data.i (Corrupted!): %d\n", data.i);

    return 0;
}

🌼 Intermediate Example: Production Tagged Union Variant Pattern

#include <stdio.h>
#include <string.h>

typedef enum { TYPE_INT, TYPE_FLOAT, TYPE_STRING } FieldType;

typedef struct {
    FieldType type;
    union {
        int i_val;
        float f_val;
        char str_val[32];
    } payload;
} GenericField;

void print_field(const GenericField *field) {
    if (field == NULL) return;

    switch (field->type) {
        case TYPE_INT:
            printf("Integer Field: %d\n", field->payload.i_val);
            break;
        case TYPE_FLOAT:
            printf("Float Field  : %.2f\n", field->payload.f_val);
            break;
        case TYPE_STRING:
            printf("String Field : \"%s\"\n", field->payload.str_val);
            break;
    }
}

int main(void) {
    GenericField f1 = {.type = TYPE_INT, .payload.i_val = 1024};
    GenericField f2 = {.type = TYPE_STRING};
    snprintf(f2.payload.str_val, sizeof(f2.payload.str_val), "C11 ISO Standard");
    f2.type = TYPE_STRING;

    print_field(&f1);
    print_field(&f2);
    return 0;
}

🌲 Advanced Example: Type Punning Float IEEE-754 Bit Inspection

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

// Type Punning Union to inspect IEEE-754 raw binary bit patterns
typedef union {
    float f;
    uint32_t raw_bits;
} FloatPun;

int main(void) {
    FloatPun pun;
    pun.f = -12.375f;

    printf("Float Value    : %f\n", pun.f);
    printf("Hex Raw Bits   : 0x%08X\n", pun.raw_bits);
    printf("Sign Bit (b31) : %u\n", (pun.raw_bits >> 31) & 1);
    return 0;
}

🔍 Line-by-Line Explanation

  • sizeof(union Data): Evaluates to 20 bytes (the size of its largest member char str[20]).
  • data.f = 220.5f;: Overwrites the shared 20-byte memory block, corrupting the previous integer value in data.i.
  • pun.raw_bits: Reinterprets the exact same 32-bit floating-point bit pattern as an unsigned integer without converting values.

💻 Expected Terminal Output

sizeof(union Data) = 20 bytes
data.i address: 0x7ffd5820a110 | Value: 100
data.f address: 0x7ffd5820a110 | Value: 220.5
data.i (Corrupted!): 1130102784
Integer Field: 1024
String Field : "C11 ISO Standard"
Float Value    : -12.375000
Hex Raw Bits   : 0xC1460000
Sign Bit (b31) : 1

⚠️ Common Mistakes & Pitfalls

  • Reading Inactive Union Members: Reading member A after writing to member B yields garbage or implementation-defined results. Always track active members using a tagged enum!
  • Confusing Struct vs Union Size Rules: Expecting a union size to equal the sum of its member sizes.

📌 Important Rules & Limitations

  • All members of a union share the exact same starting RAM address.
  • A union holds a valid value for only one member at any given moment.

🌐 Multilingual Explanation: English

A union shares a single memory location across all its members, reserving space for the largest member. Use tagged unions (combining an enum tag and union inside a struct) to track active variant data safely.

🌐 Multilingual Explanation: Hindi (Roman Script)

Union mein saare members ek hi shared RAM location ko use karte hain. Iska size uske sabse bade member ke barabar hota hai. Ek waqt mein sirf ek hi member valid value hold kar sakta hai.

🌐 Multilingual Explanation: Marathi (Roman Script)

Union madhye sagle members ekach memory location share kartat. Tyacha size sarvat mothya member evdha asto.

❓ Practice Questions

  1. What is the difference in memory allocation between a struct and a union?
  2. What is a tagged variant union and why is it used?
  3. What is type punning in C?

🚀 Practical Coding Challenge

Write a C program named tagged_sensor_data.c that uses a tagged union to store either a temperature (float), pressure (double), or error_code (int), and writes a function to display the active sensor payload.

🧭 Navigation & Breadcrumbs

← Module 14 Guide | Next: 02. Bit-Fields & Hardware Registers →