Professional Study Questions
Multiple Choice · Week 43: Working in an Existing Codebase
Question 1: Exit Code 125 In Bisect
You run git bisect run ./check.sh. For one commit in the middle of the range the project does not even compile, and the script exits with status 125. What does git do with that commit?
B: exit code 125 tells git bisect run that the commit cannot be tested, so it is skipped rather than judged. Without it, a commit that fails to build is blamed and the search converges on the wrong change.
Output Question · Week 44: Collaborative Development and Code Review
Question 2: The Inverted strcmp
A reviewer compared a buggy condition with the intended one. What does this program print?
#include <stdio.h> #include <string.h> int main(void) { const char *keys[] = { "timeout", "name", "retries" }; for (int i = 0; i < 3; i++) { int buggy = strcmp(keys[i], "timeout") ? 1 : 0; int fixed = strcmp(keys[i], "timeout") == 0 ? 1 : 0; printf("%-8s buggy=%d fixed=%d\n", keys[i], buggy, fixed); } return 0; }
Show answer
timeout buggy=0 fixed=1 name buggy=1 fixed=0 retries buggy=1 fixed=0
strcmp returns 0 when the strings are equal, so the bare condition is true for every key except "timeout". In the reviewed patch this made every other key set the timeout. The compiler cannot warn about it.
Classic Question · Week 44: Collaborative Development and Code Review
Question 3: Reviewing Only The Green Lines
A pull request is mostly additions, but it also deletes one line, if (len >= sizeof buf) return -1;, as a "cleanup". Why is it risky to review only the added lines of a C diff? Name three checks from a memory-safety review list and the defect each one catches.
Show answer
Removing code can introduce a defect just as adding code can, and the eye is drawn to additions. A deleted bounds check, free or NULL guard leaves no trace in the added half, so it is visible only in the removed lines. Read the red half as carefully as the green, and run git log -S on the deleted guard to see which bug it fixed.
Three checks from the list: (1) every allocation is checked for NULL, which catches a null dereference on failure; (2) every buffer write is bounded and has room for the terminator, which catches stack and heap overflows from strcpy or an unbounded %s; (3) every path, including early returns, frees what it allocated, which catches leaks and, with a cleanup label, double frees.
Multiple Choice · Week 45: Packaging and Distributing C Libraries
Question 4: A Silent ABI Break
A shared library libfoo.so.2 ships a public header. Which change to that header keeps every existing program compiling but still breaks the ABI of programs that are already built?
C: callers compiled against the old header use the old size and offsets of the visible struct, so a new member makes them read and write the wrong bytes while their source still compiles. A new function is safe, and a rename or a new parameter breaks the API too, so the compiler reports it.
Output Question · Week 46: ABI and Interfacing with Other Languages
Question 5: A Callback With Context
C code offers a visitor callback with a void * context, the pattern recommended for foreign callers. What does this program print?
#include <stdio.h> #include <stddef.h> typedef int (*Visitor)(double value, void *context); typedef struct { double total; int seen; } Acc; static int add_until_negative(double value, void *context) { Acc *a = context; if (value < 0.0) return 1; a->total += value; a->seen++; return 0; } static void each(const double *values, size_t count, Visitor visit, void *context) { for (size_t i = 0; i < count; i++) { if (visit(values[i], context) != 0) break; } } int main(void) { const double data[] = { 1.5, 2.5, 4.0, -1.0, 8.0 }; Acc acc = { 0.0, 0 }; each(data, 5, add_until_negative, &acc); printf("seen=%d total=%.1f\n", acc.seen, acc.total); return 0; }
Show answer
seen=3 total=8.0
A non-zero return from the visitor stops the iteration, so 1.5, 2.5 and 4.0 are added and the 8.0 after the negative value is never visited. All state travels through the explicit context pointer, with no globals.
Multiple Choice · Week 47: Event-Driven and Scalable I/O
Question 6: The Idle Server At 100 Percent
A single-threaded epoll server with one connected, idle client uses 100% of a core. Every client socket was registered with EPOLLIN | EPOLLOUT and the registration is never changed. What is the most likely cause?
A: a socket with room in its send buffer is writable nearly all the time, so epoll_wait keeps returning immediately and the loop spins. Ask for writability only while output is pending. An undrained edge-triggered socket makes a connection hang, not spin, and epoll is O(ready), not O(n).
Output Question · Week 47: Event-Driven and Scalable I/O
Question 7: Framing Lines From A Stream
A stream has no message boundaries, so the event-loop server keeps leftover bytes between reads. What does this program print?
#include <stdio.h> #include <string.h> #define BUF_SIZE 16 static char in[BUF_SIZE]; static size_t in_used; static void feed(const char *chunk) { size_t n = strlen(chunk); memcpy(in + in_used, chunk, n); in_used += n; char *start = in; char *nl; while ((nl = memchr(start, '\n', (size_t)(in + in_used - start))) != NULL) { printf("line: %.*s\n", (int)(nl - start), start); start = nl + 1; } size_t leftover = (size_t)(in + in_used - start); memmove(in, start, leftover); in_used = leftover; printf("kept %zu byte(s)\n", in_used); } int main(void) { feed("ab"); feed("c\nde"); feed("f\ng"); feed("\n"); return 0; }
Show answer
kept 2 byte(s) line: abc kept 2 byte(s) line: def kept 1 byte(s) line: g kept 0 byte(s)
A line may arrive in pieces, so incomplete data stays in the buffer and is moved to the front after each read. "abc" is complete only when the second chunk brings the newline, and "g" only when the last chunk does.
Multiple Choice · Week 48: Fuzzing and Security Testing
Question 8: Fuzzing Without Sanitizers
A libFuzzer target for a C parser is built with -fsanitize=fuzzer only. It runs for hours and reports nothing, although the parser has a heap overflow in a rarely used branch. Why can that happen?
B: a fuzzer only observes crashes, hangs and aborts. Most C memory errors corrupt a neighbor and let the program finish normally. AddressSanitizer and UBSan turn those silent defects into immediate failures, so the fuzzer supplies the inputs and the sanitizer supplies the detection.
Multiple Choice · Week 49: Embedded C and Cross-Compilation
Question 9: Where Globals Live In The Image
On a bare-metal Cortex-M target, a program defines the two globals below. Which statement about the firmware image and the startup code is correct?
static uint32_t boot_marker = 0xDEADBEEF; static uint32_t counter;
D: boot_marker lives in .data, so its initial value sits in flash and the reset handler copies it to RAM. counter lives in .bss, which takes no space in the image: only its size is recorded and the reset handler clears that much RAM. RAM is not initialized at power-on.
Multiple Choice · Week 50: Memory-Mapped I/O and Hardware Registers
Question 10: Clearing A Write-One-To-Clear Flag
The manual says bit 4 of ICR is write-one-to-clear and other bits of the same register are also write-one-to-clear flags. A colleague writes the line below to acknowledge only that interrupt. What is wrong with it?
UART0->ICR |= ICR_RXIC; /* ICR_RXIC is bit 4 */B: for a write-one-to-clear register the read returns every pending flag, and writing that value back writes a 1 to each of them. The correct code writes only the bit you mean: UART0->ICR = ICR_RXIC;. The usual preserve-the-others reasoning is backwards for these registers.
Multiple Choice · Week 51: Interrupts and Real-Time Behavior
Question 11: A Torn 64-Bit Read
On a 32-bit core, an ISR increments the counter below every millisecond. Main code runs uint64_t now = micros; with interrupts enabled. What can go wrong?
static volatile uint64_t micros;
C: volatile only forces each access to really touch memory. It gives no atomicity, and a 64-bit read on a 32-bit core is two instructions. Read it inside a critical section or use an atomic type.
Output Question · Week 51: Interrupts and Real-Time Behavior
Question 12: A Ring Buffer Holds One Less
This single-producer, single-consumer ring buffer has 8 slots and treats head equal to tail as empty. What does the program print?
#include <stdio.h> #include <stdint.h> #include <stdbool.h> #define RING_SIZE 8 static uint8_t data[RING_SIZE]; static uint8_t head, tail; static bool push(uint8_t v) { uint8_t next = (uint8_t)((head + 1u) % RING_SIZE); if (next == tail) return false; data[head] = v; head = next; return true; } static bool pop(uint8_t *out) { if (tail == head) return false; *out = data[tail]; tail = (uint8_t)((tail + 1u) % RING_SIZE); return true; } int main(void) { int accepted = 0; for (uint8_t v = 1; v <= 10; v++) { if (push(v)) accepted++; } printf("accepted %d of 10\n", accepted); uint8_t x; for (int i = 0; i < 3 && pop(&x); i++) printf("%d ", x); printf("\n"); for (uint8_t v = 11; v <= 14; v++) { printf("push %d: %s\n", v, push(v) ? "ok" : "refused"); } while (pop(&x)) printf("%d ", x); printf("\n"); return 0; }
Show answer
accepted 7 of 10 1 2 3 push 11: ok push 12: ok push 13: ok push 14: refused 4 5 6 7 11 12 13
The buffer must keep one slot unused to tell full from empty, so 8 slots hold 7 values. After three pops there is room for three more, so 14 is refused. The indices wrap with the modulo, and the oldest values come out first. Each line ends with a space after the last number.
Multiple Choice · Week 52: Linker Scripts and Firmware Memory Layout
Question 13: Reading A Linker Symbol
A linker script defines _data_start = .;. C code declares and uses the symbol as shown. What does the second line do?
extern uint32_t _data_start;
uint32_t v = _data_start;D: the linker records only an address, so the declaration describes a variable located at that address. Reading it reads whatever bytes are there. To get the address write &_data_start, or declare the symbol as an array so that the name already is the address.
Output Question · Week 53: Constrained-Resource Programming
Question 14: Q16.16 Fixed-Point Arithmetic
This program uses the Q16.16 format from the notes, with a 64-bit intermediate in the multiplication. What does it print? Note the last line.
#include <stdio.h> #include <stdint.h> typedef int32_t q16_t; #define Q16_SHIFT 16 #define INT_TO_Q16(n) ((q16_t)((n) * (1 << Q16_SHIFT))) static q16_t q16_mul(q16_t a, q16_t b) { return (q16_t)(((int64_t)a * b) >> Q16_SHIFT); } static q16_t q16_div(q16_t a, q16_t b) { return (q16_t)((((int64_t)a) << Q16_SHIFT) / b); } static void show(const char *label, q16_t q) { unsigned whole = (unsigned)(q >> Q16_SHIFT); unsigned frac = ((unsigned)(q & 0xFFFF) * 1000u) >> Q16_SHIFT; printf("%-6s raw=%ld %u.%03u\n", label, (long)q, whole, frac); } int main(void) { q16_t a = INT_TO_Q16(3); q16_t b = q16_div(INT_TO_Q16(1), INT_TO_Q16(4)); q16_t c = q16_div(INT_TO_Q16(1), INT_TO_Q16(10)); show("a", a); show("b", b); show("a*b", q16_mul(a, b)); show("a/b", q16_div(a, b)); show("1/10", c); return 0; }
Show answer
a raw=196608 3.000 b raw=16384 0.250 a*b raw=49152 0.750 a/b raw=786432 12.000 1/10 raw=6553 0.099
3.0 is 3 * 65536 and 0.25 is 16384. The product of the raw values is a Q32.32 number, so the 64-bit intermediate shifted right by 16 gives 49152, which is 0.75. One tenth is not representable: 65536 / 10 truncates to 6553, which prints as 0.099. All values are non-negative here, so the right shifts are well defined.
Classic Question · Week 53: Constrained-Resource Programming
Question 15: Pools Instead Of malloc
Why do embedded coding standards forbid malloc after initialization, and how does a fixed-block pool solve the problem? What does the pool cost you?
Show answer
The decisive reason is fragmentation: a device that runs for months and allocates and frees varying sizes ends up with free memory in pieces too small to use, and nothing restarts it. A general allocator also has unbounded allocation time, which breaks deadlines, and failure has nowhere to be reported. It is impossible to prove that a general heap cannot run out.
A fixed-block pool keeps every block the same size on a free list stored inside the free blocks, so any free block satisfies any request. Allocation and release are a few pointer assignments with identical timing and no search or coalescing, and fragmentation cannot happen. The only failure is honest exhaustion: pool_alloc returns NULL.
The cost is flexibility: variable-sized objects need one pool per size class, spare blocks are wasted memory, and the pool needs a critical section if an interrupt can allocate.
Multiple Choice · Week 54: Real-Time Operating Systems
Question 16: Priority Inversion With A Semaphore
A low-priority task holds a binary semaphore that protects shared data. A high-priority task then blocks on it, and a medium-priority task that never blocks becomes ready. What happens, and what is the usual remedy?
B: the medium task preempts the owner, so the high task waits behind a task it does not interact with. A binary semaphore has no owner and no inheritance. A mutex records its owner and temporarily raises it to the waiter's priority, which bounds the wait. This is what reset Mars Pathfinder.
Classic Question · Week 54: Real-Time Operating Systems
Question 17: Superloop Or RTOS
A device runs one superloop with four functions, and one of them takes 50 ms. When is that design still correct, and when should you move to an RTOS? Say what the move costs.
Show answer
A superloop is correct while every deadline is met. It has no concurrency bugs and no per-task stacks, and it is the right design for most small devices. Its flaw is structural: every task's period is the sum of all the tasks' execution times, so a 50 ms operation delays a 10 ms sensor read to about 54 ms, and no tuning of the individual functions fixes that.
Move to an RTOS when you can point at a measured deadline the superloop demonstrably misses and neither a state machine nor an interrupt can fix it. A preemptive scheduler then runs the sensor task first and does the slow work in the gaps.
The cost is roughly ten to fifteen kilobytes of flash plus a stack per task, and every concurrency hazard returns on a chip with no memory protection: races, deadlock, priority inversion and silent stack overflow.
Multiple Choice · Week 55: Embedded Debugging and Testing
Question 18: Why The Firmware Takes A Hal
protocol_poll(Protocol *p) reads bytes and writes replies only through function pointers stored in a Hal struct, and register access lives in a separate device file. What is the main benefit?
C: with the hardware behind a boundary, the protocol logic becomes ordinary C. A fake Hal scripts the input, captures the output and controls time, so tests, sanitizers and fuzzing run on the host. Only the thin driver layer needs the simulator or the device.
Output Question · Week 56: Maintaining Long-Lived C Codebases
Question 19: Pinning The Parser Behavior
This is the modernized parse_record from the notes, which keeps the legacy behavior of returning 0 for a malformed number. What does the program print?
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <stdbool.h> static const char *skip_space(const char *s) { while (*s == ' ' || *s == '\t') s++; return s; } static void trim_trailing(char *s) { size_t n = strlen(s); while (n > 0 && (s[n - 1] == ' ' || s[n - 1] == '\t')) s[--n] = '\0'; } static bool parse_long(const char *text, long *out) { if (text == NULL || *text == '\0') return false; errno = 0; char *end; long v = strtol(text, &end, 10); if (end == text || errno == ERANGE) return false; *out = v; return true; } static bool parse_record(const char *line, char *out_name, size_t name_size, int *out_value) { char work[256]; if ((size_t)snprintf(work, sizeof work, "%s", line) >= sizeof work) return false; char *equals = strchr(work, '='); if (equals == NULL) return false; *equals = '\0'; char *name = work; while (*name == ' ' || *name == '\t') name++; trim_trailing(name); if ((size_t)snprintf(out_name, name_size, "%s", name) >= name_size) return false; const char *value_text = skip_space(equals + 1); long v; *out_value = parse_long(value_text, &v) ? (int)v : 0; return true; } int main(void) { const char *inputs[] = { "timeout = 30", " name = 42 ", "noequals", "= 5", "empty =", "x = abc" }; for (size_t i = 0; i < sizeof inputs / sizeof inputs[0]; i++) { char name[32] = { 0 }; int value = -999; bool ok = parse_record(inputs[i], name, sizeof name, &value); printf("\"%s\" -> %d \"%s\" %d\n", inputs[i], ok ? 1 : 0, name, value); } return 0; }
Show answer
"timeout = 30" -> 1 "timeout" 30 " name = 42 " -> 1 "name" 42 "noequals" -> 0 "" -999 "= 5" -> 1 "" 5 "empty =" -> 1 "empty" 0 "x = abc" -> 1 "x" 0
A line with no equals sign is rejected and leaves both outputs untouched. An empty name is accepted, and an empty or non-numeric value becomes 0, which is indistinguishable from a real 0. These are the questionable results that a characterization test pins before any behavior fix.
Classic Question · Week 56: Maintaining Long-Lived C Codebases
Question 20: Characterization Tests Before Refactoring
You inherit an untested 1990s C function with no specification. What is a characterization test, how do you build one, and why do you keep behavior that you believe is a bug?
Show answer
A characterization test records what the code currently does, not what it should do. Call the function with a wide range of inputs, record the outputs whatever they are, and turn the recordings into assertions. Run them under coverage and add cases until the function is covered.
Wrong behavior is pinned deliberately. If a test fails during the refactoring, you then know the refactoring caused it. Mixing a fix into the same step means a failing test cannot say which change broke it.
The refactoring then proceeds in small steps with the tests run after each one. The bug is fixed afterwards in a separate commit that updates exactly the assertions that encoded the old behavior, so it can be reviewed and reverted on its own.