PROGRAMMING IN C/Student Engineering Notebook
Page 08·notes
STRUCTURES, UNIONS & MEMORY ALIGNMENT—~28 MIN READ

Unions, Bit-Fields & Dynamic Memory Management

“Union memory overlap, bitfield packing, malloc, calloc, realloc, and free.”

1.Unions & Bit-Fields

Unions:

- In a union, all members share the EXACT SAME starting memory address.

- Size of union = size of its largest member (padded to alignment requirement).

- Used for memory conservation and type punning (e.g. testing endianness).

Bit-Fields:

- Allow variables of specified bit widths inside structures (e.g. unsigned int flag : 1;).

- Multiple bit-fields pack into a single machine word.

2.Dynamic Memory Management: Heap Mechanics

- malloc(size): Allocates size uninitialized bytes on Heap. Returns void* (or NULL on failure).

- calloc(n, size): Allocates and initializes all bytes to ZERO.

- realloc(ptr, new_size): Resizes existing block, potentially moving it to a new heap address.

- free(ptr): Returns memory to heap. Does NOT set pointer to NULL, creating a dangling pointer!

WORKED NUMERICAL · STUDENT DERIVATION✎ Key Takeaway: Only one member holds a meaningful value at a time; reading another member reinterprets the same bytes.

Worked example: the size of a union

Problem Statement:
Assuming 4-byte ints: what is sizeof(union { int i; char c[4]; double d; }) on a platform where double is 8 bytes, aligned to 8?
Step 1: Members share storage

A union is as large as its largest member, padded to the strictest alignment.

Step 2: Largest member

double d: 8 bytes.

Step 3: Alignment

8 is already a multiple of 8.

Final Answer:8 bytes
STUDENT PRACTICE · CONCEPT DRILL

Practice: test yourself

Original practice questions in the GATE style, with worked explanations. Not past-paper questions.

Problem 1 · FOUNDATION

Assuming 4-byte ints, what is sizeof(union { int i; char c[4]; })?

bytes
Problem 2 · TRICKY

struct { unsigned a : 3; } s; s.a = 9; What is s.a?

Problem 3 · FOUNDATION

A memory leak happens when:

SOURCE TRANSPARENCY & CITATIONS

Primary Academic References & Exam Sources

Every concept in Notes From a B.Tech Brain is synthesized from authoritative academic texts, seminal peer-reviewed research, verified exam archives, and renowned university lectures.

Curated University Lecture Series
Expert C Programming: Deep C Secrets ·
LECTURE SERIES
RECOMMENDED YOUTUBE EDUCATORS & FULL-COURSE PLAYLISTS

Curated for clarity, rigorous numerical solving, and semester excellence:

Neso Academy · C Programming Full Course↗Instructor: Neso Academy · Covers: Data types, pointers, arrays, functions, recursion, file I/O

Systematic beginner-to-advanced C with clear examples.

Open YouTube↗
Jenny's Lectures CS/IT · C Programming↗Instructor: Jenny's Lectures · Covers: Arrays, strings, pointers, structures, file handling, preprocessor

Clear step-by-step C explanations — great for semester lab preparation.

Open YouTube↗