Unions, Bit-Fields & Dynamic Memory Management
“Union memory overlap, bitfield packing, malloc, calloc, realloc, and free.”
1.Unions & Bit-Fields
§ 4.1.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
§ 4.2.- 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 example: the size of a union
A union is as large as its largest member, padded to the strictest alignment.
double d: 8 bytes.
8 is already a multiple of 8.
Practice: test yourself
Original practice questions in the GATE style, with worked explanations. Not past-paper questions.
Assuming 4-byte ints, what is sizeof(union { int i; char c[4]; })?
struct { unsigned a : 3; } s; s.a = 9; What is s.a?
A memory leak happens when:
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 for clarity, rigorous numerical solving, and semester excellence:
Systematic beginner-to-advanced C with clear examples.
Clear step-by-step C explanations — great for semester lab preparation.