Advanced Study Questions
Multiple Choice · Week 29: Building Programs and Libraries
Question 1: Reading nm Output
Running nm helpers.o lists a function grow with the letter t and a function stack_create with the letter T. What does the difference tell you?
A: both letters mean the symbol is defined in the text section of this object. Uppercase means external linkage; lowercase means internal linkage, which is what static produces. An undefined symbol would be shown as U.
Multiple Choice · Week 29: Building Programs and Libraries
Question 2: Library After the Objects
gcc -lintarray main.c -o app fails with "undefined reference to intarray_create", although libintarray.a contains that function. What is the fix?
B: the linker reads its arguments from left to right and takes from a library only the members that satisfy symbols already known to be undefined. Listed first, the library is examined before main.c has asked for anything, so nothing is extracted. Libraries go after the files that use them.
Output Question · Week 30: Function Pointers, Callbacks, and Generic Programming
Question 3: Sorting and Dispatching
What does this program print?
#include <stdio.h> #include <stdlib.h> static int cmp_int(const void *a, const void *b) { int x = *(const int *)a; int y = *(const int *)b; return (x > y) - (x < y); } static int add(int a, int b) { return a + b; } static int mul(int a, int b) { return a * b; } typedef struct { const char *name; int (*fn)(int, int); } Command; int main(void) { int v[] = { 30, -5, 12, 7, -20 }; size_t n = sizeof v / sizeof v[0]; qsort(v, n, sizeof v[0], cmp_int); for (size_t i = 0; i < n; i++) { printf("%d ", v[i]); } printf("\n"); int key = 12; int *hit = bsearch(&key, v, n, sizeof v[0], cmp_int); printf("index of 12: %td\n", hit - v); key = 8; printf("8 found: %d\n", bsearch(&key, v, n, sizeof v[0], cmp_int) != NULL); static const Command table[] = { { "add", add }, { "mul", mul } }; for (size_t i = 0; i < 2; i++) { printf("%s(6, 7) = %d\n", table[i].name, table[i].fn(6, 7)); } return 0; }
Show answer
-20 -5 7 12 30 index of 12: 3 8 found: 0 add(6, 7) = 13 mul(6, 7) = 42
qsort orders the array with the comparator, and bsearch works because the array is now sorted by that same comparator. The table stores one function pointer per row, so table[i].fn(6, 7) calls add and then mul. The first line ends with a space because every number is followed by one.
Multiple Choice · Week 30: Function Pointers, Callbacks, and Generic Programming
Question 4: Variadic Promotions
Inside a variadic function that was called as f(2, 1.5f, 2.5f), how must the two float arguments be read?
B: arguments in the variable part undergo the default promotions, so a float arrives as a double (and anything narrower than int arrives as int). Asking va_arg for float is always wrong, and nothing at run time checks the type you name.
Multiple Choice · Week 31: Command-Line Interfaces and the Environment
Question 5: Ways Out of a Program
A program registers a cleanup function with atexit that deletes a temporary file. In which case does the file still get deleted?
C: exit (like returning from main) runs the registered handlers and flushes the streams. _Exit and abort skip both, and a fatal signal never reaches the handlers, so cleanup that must always happen cannot rely on atexit alone.
Output Question · Week 32: Linked Data Structures
Question 6: Removing with a Pointer to Pointer
What does this program print?
#include <stdio.h> #include <stdlib.h> typedef struct Node { int value; struct Node *next; } Node; static void push_front(Node **head, int value) { Node *n = malloc(sizeof *n); if (n == NULL) exit(1); n->value = value; n->next = *head; *head = n; } static void remove_value(Node **head, int value) { for (Node **link = head; *link != NULL; link = &(*link)->next) { if ((*link)->value == value) { Node *dead = *link; *link = dead->next; free(dead); return; } } } static void print_list(const Node *n) { for (; n != NULL; n = n->next) { printf("%d ", n->value); } printf("\n"); } int main(void) { Node *head = NULL; push_front(&head, 30); push_front(&head, 20); push_front(&head, 20); push_front(&head, 10); print_list(head); remove_value(&head, 20); print_list(head); remove_value(&head, 10); print_list(head); remove_value(&head, 99); remove_value(&head, 30); print_list(head); printf("empty: %d\n", head == NULL); while (head != NULL) { Node *next = head->next; free(head); head = next; } return 0; }
Show answer
10 20 20 30 10 20 30 20 30 20 empty: 0
The first remove_value(&head, 20) removes only the first node holding 20, because the function returns after one removal. Removing 10 changes the caller's head through link with no special case, removing 99 changes nothing, and the list ends with the second 20, so it is not empty.
Multiple Choice · Week 33: Trees, Hash Tables, and Abstract Data Types
Question 7: Sorted Input and Trees
A plain binary search tree receives the keys 1, 2, 3, ..., 1000 in that order. What is the shape of the result, and what does a lookup cost?
B: every new key is larger than all earlier ones, so it goes to the right of the last node and the tree degenerates into a linked list. Lookup becomes O(n). A plain tree has no worst-case guarantee; self-balancing variants such as AVL and red-black trees restore it by rotating.
Classic Question · Week 33: Trees, Hash Tables, and Abstract Data Types
Question 8: Growing a Hash Table
A chained hash table doubles its number of buckets when the load factor passes about 0.75. Why must every existing entry be rehashed, and why is insertion still O(1) amortized?
Show answer
An entry's bucket is hash(key) % bucket_count. When the bucket count changes, the result changes for nearly every key, so an entry left in its old bucket would be unreachable at the index the lookup now computes. Growing therefore costs O(n).
Because the count doubles each time, that expensive step happens rarely: the total work of all resizes over n insertions is proportional to n. Spread over the insertions, each one costs O(1) on average, as with the growable array.
Multiple Choice · Week 34: Performance and Memory Layout
Question 9: Loop Order and Cache Lines
A program sums every element of a large int m[ROWS][COLS] twice, once with the row index in the outer loop and once with the column index in the outer loop. Both give the same sum. Which statement is correct?
C: C stores arrays row by row, and the hardware fetches whole cache lines of about 64 bytes. The row-outer loop uses every int of each fetched line and lets the prefetcher help; the column-outer loop jumps a whole row at each step. The operation count is the same, but the number of cache misses is not.
Output Question · Week 35: Debugging, Testing, and Analysis
Question 10: A Test Macro in Action
What does this program print?
#include <stdio.h> static int tests_run = 0, tests_failed = 0; #define CHECK(cond) do { \ tests_run++; \ if (!(cond)) { \ tests_failed++; \ printf("FAIL: %s\n", #cond); \ } \ } while (0) static int clamp(int x, int lo, int hi) { if (x < lo) return lo; if (x > hi) return hi; return x; } int main(void) { CHECK(clamp(5, 0, 10) == 5); CHECK(clamp(-3, 0, 10) == 0); CHECK(clamp(10, 0, 10) == 9); if (tests_run > 2) CHECK(clamp(99, 0, 10) == 10); else CHECK(0); printf("%d run, %d failed\n", tests_run, tests_failed); return tests_failed != 0; }
Show answer
FAIL: clamp(10, 0, 10) == 9 4 run, 1 failed
The macro stringifies the failing condition with #cond, so the report shows the tested expression as it was written. Wrapping the body in do { ... } while (0) lets CHECK(...); stand safely in front of else. The first, second and fourth checks pass; the third fails because clamp returns 10, not 9.
Output Question · Week 36: Undefined Behavior and Secure Coding
Question 11: Checking Before Adding
What does this program print? (INT_MAX and INT_MIN are the largest and smallest int values.)
#include <stdio.h> #include <limits.h> static int add_fits(int a, int b) { if (b > 0 && a > INT_MAX - b) return 0; if (b < 0 && a < INT_MIN - b) return 0; return 1; } int main(void) { printf("%d\n", add_fits(INT_MAX, 1)); printf("%d\n", add_fits(INT_MAX, -1)); printf("%d\n", add_fits(INT_MIN, -1)); printf("%d\n", add_fits(INT_MIN, 1)); printf("%d\n", add_fits(5, 6)); unsigned int u = UINT_MAX; u = u + 1; printf("%u\n", u); return 0; }
Show answer
0 1 0 1 1 0
add_fits tests the operands against the limits before any addition happens, so no signed overflow ever occurs. INT_MAX + 1 and INT_MIN + (-1) are refused (0), the other sums fit (1). The last line is 0 because unsigned arithmetic is defined to wrap around modulo 2 to the power of the width.
Multiple Choice · Week 36: Undefined Behavior and Secure Coding
Question 12: A Check the Optimizer Removes
A function contains if (a + b < a) return ERROR; to detect overflow of the int sum a + b, with b known to be non-negative. Why may an optimizing compiler delete it?
A: overflow of a signed addition is undefined behavior, so the compiler reasons as if it cannot occur; for non-negative b the sum is then never less than a and the branch is dead code. The check must come before the operation, for example by comparing a with INT_MAX - b.
Output Question · Week 37: Portability and the Machine Model
Question 13: Bytes and Characters
What does this program print? (The escape \xC3\xA9 is the UTF-8 encoding of the letter e with an acute accent.)
#include <stdio.h> #include <stdint.h> #include <inttypes.h> #include <string.h> int main(void) { uint32_t v = 0x12345678u; uint8_t b[4]; b[0] = (uint8_t)(v >> 24); b[1] = (uint8_t)(v >> 16); b[2] = (uint8_t)(v >> 8); b[3] = (uint8_t)v; for (int i = 0; i < 4; i++) { printf("%02X ", (unsigned)b[i]); } printf("\n"); uint32_t back = ((uint32_t)b[0] << 24) | ((uint32_t)b[1] << 16) | ((uint32_t)b[2] << 8) | (uint32_t)b[3]; printf("%" PRIu32 "\n", back); const char *s = "h\xC3\xA9llo"; size_t chars = 0; for (const unsigned char *p = (const unsigned char *)s; *p != '\0'; p++) { if ((*p & 0xC0) != 0x80) chars++; } printf("bytes=%zu chars=%zu\n", strlen(s), chars); return 0; }
Show answer
12 34 56 78 305419896 bytes=6 chars=5
The shifts work on the value, not on its memory representation, so the bytes come out most significant first on any host, and the decoder rebuilds 0x12345678 = 305419896. The letter e with accent takes two bytes, so strlen says 6; counting only the bytes that are not continuation bytes (10xxxxxx) gives 5 characters.
Multiple Choice · Week 37: Portability and the Machine Model
Question 14: Choosing a 64-Bit Type
A program stores file sizes up to several gigabytes in a long and runs correctly on Linux. A colleague wants to build it for 64-bit Windows. What is the problem, and the fix?
A: the standard guarantees only 32 bits for long. It is 8 bytes under LP64 (Linux, macOS) but 4 bytes under LLP64 (64-bit Windows). int64_t states the required width exactly; print it with PRId64 from <inttypes.h>.
Output Question · Week 38: Type Qualifiers, Inlining, and Modern C
Question 15: Compound Literals
What does this program print?
#include <stdio.h> struct point { int x, y; }; static inline int dist2(const struct point *p) { return p->x * p->x + p->y * p->y; } int main(void) { printf("%d\n", dist2(&(struct point){ 3, 4 })); int *a = (int[]){ 1, 2, 3 }; a[1] = 20; printf("%d %d %d\n", a[0], a[1], a[2]); int total = 0; for (int i = 0; i < 3; i++) { struct point *p = &(struct point){ i, i + 1 }; total += dist2(p); } printf("%d\n", total); return 0; }
Show answer
25 1 20 3 19
A compound literal is an unnamed object. (struct point){ 3, 4 } gives 9 + 16 = 25, and (int[]){ 1, 2, 3 } is a modifiable array, so a[1] = 20 is legal. A compound literal inside a block lasts until the end of that block, so each loop pass has its own point: 1 + 5 + 13 = 19.
Multiple Choice · Week 38: Type Qualifiers, Inlining, and Modern C
Question 16: What volatile Guarantees
Two threads execute counter++ on a global declared volatile int counter. What does volatile do for this program?
B: volatile only guarantees that each read and write really happens, in program order. It gives no atomicity and no ordering with respect to other variables, and the increment is still load, add, store. Use <stdatomic.h> or a mutex.
Multiple Choice · Week 39: Processes, Signals, and Low-Level I/O
Question 17: The Silent Pipe Reader
A parent creates a pipe, forks, and the child reads from the pipe until end of file. The parent writes its data, then waits for the child, but the child never finishes. What is the most likely cause?
C: the reader sees end of file only when every copy of the write end is closed, including the parent's own. Each process must close the pipe ends it does not use, so the parent has to close its write end before it waits.
Multiple Choice · Week 40: Network Programming with Sockets
Question 18: Meaning of recv Returning Zero
In a TCP server, recv(conn, buf, sizeof buf, 0) returns 0. What does this mean?
D: zero means end of stream, a normal close by the peer. An error returns a negative value with the reason in errno (EINTR, EAGAIN on a timeout, ECONNRESET and so on). TCP has no empty messages because it carries a byte stream.
Classic Question · Week 40: Network Programming with Sockets
Question 19: Message Boundaries over TCP
A client calls send twice, with the 5-byte messages "HELLO" and "WORLD". The server calls recv once with a 100-byte buffer. What may it receive, and how should a protocol deal with this?
Show answer
It may receive all ten bytes at once, only part of the first message, or anything in between, because TCP delivers a byte stream and keeps no record of how the data was sent. One recv is not one send.
The protocol must mark message boundaries itself, with a delimiter, a fixed size, or a length prefix, and the receiver must accumulate bytes until a complete message is present. A length prefix has to be converted with htonl and ntohl and bounded before anything is allocated, since the peer may be hostile. Sending needs a loop as well, because send can transfer less than requested.
Multiple Choice · Week 41: Concurrency and the C Memory Model
Question 20: Waiting on a Condition
Why must pthread_cond_wait be called inside a while loop that re-tests the predicate, rather than inside an if?
A: spurious wakeups are allowed, and between the signal and the moment the waiter reacquires the mutex another thread may consume what it was waiting for. Re-testing the predicate after every wakeup is the only correct pattern, and an if produces a bug that shows up rarely and under load.
Classic Question · Week 41: Concurrency and the C Memory Model
Question 21: Why a Data Race Is Undefined
Two threads execute counter++ on a shared int without any synchronization. Explain why the standard calls this undefined behavior rather than saying that the result is merely a wrong number.
Show answer
The increment is three steps (load, add, store), so two interleaved threads can lose an update. That alone would only give a wrong value. But the standard goes further: two threads accessing one object without synchronization, with at least one writing, is a data race, and a data race withdraws all requirements from the program.
The compiler may therefore keep the variable in a register, reorder the accesses, or optimize on the assumption that no race exists. Asking which interleaving happened already presumes a guarantee that the language does not give. The fix is a mutex or an atomic type from <stdatomic.h>; volatile does not help.
Classic Question · Week 42: Reading Excellent C
Question 22: Why Undefined Behavior Exists
C leaves signed integer overflow undefined instead of requiring wraparound. Give the engineering reasons, and say who pays the cost of this decision.
Show answer
Requiring wraparound would have two costs. Machines that trap on overflow or use another representation would need extra instructions on every arithmetic operation, and the optimizer could no longer assume that i + 1 > i, which is what lets it keep loop counters in registers and vectorize loops.
Leaving the case undefined gives maximum speed and portability to every correct program, and puts the cost on the rare program that actually overflows, which gets no guarantee at all. That is the bargain C makes throughout; whether it was the right one is still debated, but it is a coherent decision, not an accident.