Module 4 · 15 min read · Free chapter
Structures, unions, files and memory
A struct keeps members in order with padding for alignment, while a union's members share one block of memory. malloc gives uninitialised memory, calloc gives zeros and realloc may move the block. Losing the last pointer leaks memory, and using freed memory is undefined. Macros substitute text, so SQ(2 + 3) without brackets gives 11.
Start from zero: the reservation form
Look at a railway reservation form. It has boxes for the passenger's name, age, berth preference and fare, and together they describe one passenger. A clerk does not keep four separate piles of names, ages, berths and fares; she keeps one form per passenger.
C lets you build such a form as a structure. A struct passenger can hold a name (a string), an age (an int) and a fare (a double) under one name, so one variable describes one whole passenger.
Now suppose the number of passengers is not known in advance. The program must ask for memory while it runs, link the forms together, and save them to a file before it ends. That is the rest of this chapter: unions, dynamic memory, files and the preprocessor.
Why it matters. Real data, from bank accounts to train bookings, comes as records with many fields. Linked lists, trees and graphs are all built from structures that point to one another.
struct, typedef and enum
A structure type is declared once and then used like any other type. Members are reached with the dot operator on a structure variable, and with the arrow operator on a pointer to a structure. The arrow is only a shorthand: p->x means (*p).x, where the brackets matter because . binds tighter than *.
typedef struct point { int x, y; } Point;
Point p = {3, 4}, q;
q = p; /* copies every member */
q.x = 10;
printf("%d %d\n", p.x, q.x); /* prints 3 10 */
Assigning one structure to another copies all its members, so changing q later leaves p alone. A structure is also passed by value: a function that sets s.a = 99 on its parameter changes only its copy, while a function that takes struct S *s and sets s->a = 99 changes the caller's structure. Our test printed 1 for the first and 99 for the second.
typedef gives an existing type a new name, so Point and struct point are the same type. It does not create a new type, and it is often used to shorten structure and pointer types.
An enumeration names a set of integer constants. In enum colour {RED, GREEN = 5, BLUE}; the values are 0, 5 and 6, because counting starts at 0 and each constant is one more than the one before unless a value is given. Enumeration constants have type int, and sizeof(enum colour) was 4 with gcc.
Why it matters. Structures keep related data together, which makes code shorter and safer. Enumerations replace magic numbers such as 0, 1 and 2 with names such as SLEEPER, AC3 and AC2.
Padding and alignment, and unions
Why is a structure often bigger than the sum of its members? Most processors read an int fastest when its address is a multiple of 4, and a double when its address is a multiple of 8. So the compiler inserts unused padding bytes to keep each member aligned, and it may also pad the end so that arrays of the structure stay aligned.
struct A { char c; int i; char d; }; /* sizeof 12 */
struct B { int i; char c; char d; }; /* sizeof 8 */
struct C { char c; double x; }; /* sizeof 16 */
In struct A, c sits at offset 0, then 3 padding bytes push i to offset 4, d sits at offset 8, and 3 more bytes round the size up to 12. offsetof from <stddef.h> printed 4 for i and 8 for d. Putting the larger members first, as in struct B, packs the same data into 8 bytes.
The exact padding is implementation-defined; these sizes are what gcc gave on 64-bit Linux. What the standard does fix is that members stay in declaration order and the first member is at offset 0, so a GATE question must state its alignment rule.
A union looks like a structure, but all its members share the same memory, starting at the same address. So its size is that of the largest member, rounded up for alignment: union {int i; char c[4]; double d;} had size 8, and union {int i; char c[5];} also had size 8, because 5 bytes were rounded up to a multiple of 4.
Only the member written last holds a meaningful value. After u.i = 0x41424344, reading u.c[0] printed 'D' on our machine, because it stores the lowest byte first (little-endian); a big-endian machine would print 'A'.
Why it matters. Padding decides how much memory a million records take and how files and network packets are laid out. Unions save memory when only one of several fields is used at a time, as in a message that can be one of many kinds.
Self-referential structures and dynamic memory
A structure cannot contain a member of its own type, because its size would never end. But it may contain a pointer to its own type, which has a fixed size. Such a self-referential structure is the building block of linked lists and trees.
struct node { int data; struct node *next; };
struct node *push(struct node *head, int v) {
struct node *n = malloc(sizeof *n);
if (n == NULL) return head; /* allocation failed */
n->data = v;
n->next = head;
return n; /* new node becomes the head */
}
Pushing 1, 2 and 3 in turn and then walking the list printed "3 2 1", because each new node goes in front. On our machine sizeof(struct node) was 16: 4 bytes of int, 4 bytes of padding and an 8-byte pointer. The full list operations are covered in linked lists.
The nodes come from the heap through four functions in <stdlib.h>.
malloc(n)returns a pointer to n bytes whose contents are not initialised, orNULLif no memory is available.calloc(count, size)allocates bytes and sets them all to 0.realloc(p, n)resizes the block to n bytes. It may move the block and copy the old contents, so always use the pointer it returns.free(p)gives the block back;free(NULL)is allowed and does nothing.
int *a = malloc(5 * sizeof *a);
int *b = calloc(5, sizeof *b); /* b[0] to b[4] are 0 */
int *t = realloc(a, 10 * sizeof *a);
if (t != NULL) a = t; /* keep a valid if realloc fails */
free(a); a = NULL;
free(b); b = NULL;
The t variable matters. If realloc fails it returns NULL but leaves the old block untouched, so writing a = realloc(a, n) would lose the only pointer to it. Writing sizeof *a instead of sizeof(int) keeps the code right even if the type of a changes later.
Why it matters. Dynamic memory lets a program handle a hundred or a million passengers with the same code. Most crashes in C programs come from misusing these four functions.
Leaks, dangling pointers, and stack versus heap
A running C program typically divides its memory into five regions. The text segment holds the machine code, the data segment holds initialised globals and statics, and the bss segment holds globals and statics that start at zero. The heap serves malloc, and the stack holds the frames of active function calls.
| Property | Stack | Heap |
|---|---|---|
| Who frees it | automatic, when the function returns | the programmer, by calling free |
| Typical size | small and fixed per thread | large, limited by available memory |
| Speed of allocation | very fast: move the stack pointer | slower: search for a free block |
| Typical error | stack overflow from deep recursion | leaks and dangling pointers |
A memory leak happens when the last pointer to a heap block is lost before the block is freed. In the lines below the first block can never be freed again. We ran this program under a memory checker, which reported "20 bytes in 1 blocks are definitely lost".
int *p = malloc(5 * sizeof *p);
p = malloc(5 * sizeof *p); /* the first block is now unreachable */
free(p);
A dangling pointer still holds an address whose memory is no longer valid. It appears after free(p) if p is used again, and also when a function returns the address of its own local variable; gcc warned "function returns address of local variable" for such code. Using a dangling pointer, or freeing the same block twice, is undefined behaviour.
Two habits prevent most of these bugs. Set a pointer to NULL right after free, and give every malloc one clear owner who is responsible for the matching free.
Why it matters. A server that leaks a little memory on every request slowly runs out of memory and crashes after days. Dangling pointers are behind many security attacks, because freed memory may be reused for other data.
File input and output, and command-line arguments
Variables vanish when a program ends, so data that must survive is written to a file. C works with files through a FILE * pointer returned by fopen, which returns NULL if the file cannot be opened.
The mode string decides what you may do.
"r"opens an existing file for reading, and fails if the file does not exist."w"creates the file, or empties it if it exists, and opens it for writing."a"opens for appending, so every write goes to the end.- Adding
+, as in"r+","w+"or"a+", allows both reading and writing, and addingb, as in"rb", selects binary mode.
FILE *fp = fopen("marks.txt", "w");
if (fp == NULL) { perror("fopen"); return 1; }
fprintf(fp, "%s %d\n", "Asha", 82);
fprintf(fp, "%s %d\n", "Ravi", 74);
fclose(fp);
fp = fopen("marks.txt", "r");
char name[20]; int m, total = 0;
while (fscanf(fp, "%19s %d", name, &m) == 2) total += m;
fclose(fp);
printf("total %d\n", total); /* prints total 156 */
fprintf and fscanf work like printf and scanf but take the file first. fscanf returns the number of items it matched, or EOF at the end, so the loop stops cleanly; the width 19 keeps the name inside its 20-byte array. After opening the same file in "a" mode and adding one more line, a loop counting '\n' with fgetc found 3 lines.
fgetc returns an int, not a char, so that the special value EOF can be told apart from every real character. fclose flushes any data still waiting in the buffer, so a program that forgets it may lose its last writes.
Programs can also take input from the command line. With int main(int argc, char *argv[]), argc counts the words typed, including the program name. Running ./prog hello 42 gave argc = 3, argv[0] the program name, argv[1] "hello" and argv[2] "42", and argv[argc] is always a null pointer.
Why it matters. Reports, logs and saved games all depend on file I/O. Command-line arguments let one program process any file name or setting without being recompiled.
Preprocessor macros and their pitfalls
The preprocessor runs before the compiler and works on text, not on values. #define PI 3.14 replaces every later PI token with 3.14, and a function-like macro replaces its parameters word for word. It does not know about precedence, types or evaluation order.
That is the source of every macro trap. Compare an unsafe and a safe square.
#define SQ_BAD(x) x * x
#define SQ_OK(x) ((x) * (x))
#define DOUBLE(x) x + x
#define STR(x) #x
printf("%d %d\n", SQ_BAD(2 + 3), SQ_OK(2 + 3)); /* prints 11 25 */
printf("%d %d\n", 10 / SQ_BAD(2), 10 / SQ_OK(2)); /* prints 10 2 */
printf("%d\n", 3 * DOUBLE(4)); /* prints 16 */
printf("%s\n", STR(hello world)); /* prints hello world */
SQ_BAD(2 + 3) becomes 2 + 3 * 2 + 3, which is , not 25. 10 / SQ_BAD(2) becomes 10 / 2 * 2, which is 10, and 3 * DOUBLE(4) becomes 3 * 4 + 4, which is 16. So the rule is to put brackets around every parameter and around the whole body.
Brackets cannot fix side effects. SQ_OK(i++) becomes ((i++) * (i++)), which modifies i twice without a sequence point and is undefined behaviour. An inline function such as static inline int sq(int x) { return x * x; } evaluates its argument once and checks its type, so it is usually the better choice.
The preprocessor also controls what gets compiled. #ifdef NAME, #ifndef NAME, #else and #endif keep or drop blocks of code, and #undef removes a definition; in our test a line inside #ifndef PI printed only after #undef PI. Header files use this idea as an include guard, #ifndef plus #define, so that their contents are not pasted twice.
Why it matters. Macros are still everywhere in system code, for constants, debug switches and platform checks. GATE likes the unbracketed macro because the wrong answer looks so natural.
Descriptive lens: how written papers ask this
Written papers for IT officer posts, state Assistant Programmer exams and university tests ask about this topic in four ways.
- They ask you to compare a structure with a union, or
mallocwithcalloc, usually in a table with a small example. - They ask you to explain padding, memory leaks or dangling pointers and how to avoid them.
- They ask you to write a program that stores records in a structure array or a linked list and saves them to a file.
- They ask you to trace a macro expansion or a command-line program and give its output.
Practice questions (our own, not previous-year questions).
- Differentiate between a structure and a union with a memory diagram, and give one situation where a union is the better choice. (10 marks)
- Write a C program that reads the names and marks of n students from a file, stores them in dynamically allocated structures and prints the topper. (15 marks)
- Explain memory leaks and dangling pointers in C with code examples, and describe practices that prevent them. (10 marks)
Answer plan for question 3.
- Explain that heap memory obtained with
mallocstays allocated untilfreeis called, unlike stack memory, which is released when a function returns. - Define a memory leak as losing the last pointer to a heap block before freeing it, and show the example of reassigning p to a second
malloc. - State that a leaking long-running program, such as a server, slowly exhausts memory.
- Define a dangling pointer as a pointer to memory that is no longer valid, and show both use after
freeand returning the address of a local variable. - State that using a dangling pointer or freeing a block twice is undefined behaviour.
- List the prevention habits: set pointers to
NULLafterfree, give each block one owner, check every allocation, and test with a memory checker.
Quick revision
- Members are reached with
.on a structure and->on a pointer, andp->xmeans(*p).x. - Structure assignment copies all members, and structures are passed by value.
- Padding is implementation-defined; with gcc on 64-bit Linux,
{char; int; char}took 12 bytes and{int; char; char}took 8. - A union's members share memory, so its size is that of the largest member, rounded for alignment.
- Enumeration constants are ints counting from 0, and
typedefonly makes a new name. - A self-referential structure holds a pointer to its own type, never a member of its own type.
mallocgives uninitialised memory,callocgives zeros,reallocmay move the block, andfree(NULL)is harmless.- A leak loses the last pointer to a block, and a dangling pointer points to memory that is no longer valid.
- Stack memory is freed automatically on return, while heap memory lasts until
free. fopenreturnsNULLon failure,"w"empties a file,"a"appends, andfcloseflushes.argccounts the program name too, andargv[argc]is a null pointer.- Macros substitute text, so bracket every parameter and the whole body, and never pass
i++.