Staff Embedded Developer Interview Preparation Guide - Airbnb
Airbnb's interview process for technical roles emphasizes practical problem-solving, culture fit assessment, and real-world system design. For a staff-level embedded developer position, expect a comprehensive evaluation spanning recruiter screening, multiple technical phone screens, and 5-7 onsite rounds covering low-level systems programming, embedded architecture design, hardware-software integration, performance optimization, and deep culture alignment with Airbnb's values around execution, bias to action, and collaboration with hardware teams.
Interview Rounds
Recruiter Screening
What to Expect
Initial conversation with Airbnb recruiter to assess background, experience level, interest alignment, and potential fit for the staff-level embedded developer role. This is a brief screening to verify qualifications and understand your career trajectory in embedded systems, particularly experience with hardware integration, team leadership, and large-scale systems. Recruiter will also explain the interview process and address initial questions.
Tips & Advice
Be clear about your expertise in embedded systems and any specific domain experience (IoT, automotive, consumer devices, etc.). Mention concrete examples of systems you've built or optimized at scale. Discuss your experience mentoring junior engineers and leading hardware-software integration efforts. Show enthusiasm for Airbnb's marketplace and hardware challenges. Clarify your understanding of what staff-level means: leading complex embedded initiatives, mentoring senior engineers, and making architectural decisions.
Focus Topics
Knowledge of Airbnb's business and IoT applications
Understanding of how embedded systems and IoT might apply to Airbnb's marketplace, guest experience, or host tools
Practice Interview
Study Questions
Career trajectory and embedded systems expertise
Overview of your progression in embedded development, key projects, and level of hardware-software integration experience
Practice Interview
Study Questions
Leadership and mentorship experience
Examples of leading embedded systems teams, mentoring junior engineers, and driving architectural decisions
Practice Interview
Study Questions
Technical Phone Screen 1 - Low-Level Systems Programming
What to Expect
First technical phone interview focusing on core embedded systems programming skills. You will be asked to solve practical embedded systems problems in C or C++, likely involving memory management, bit manipulation, hardware register access, or simple firmware logic. The interviewer will evaluate your coding style, understanding of hardware constraints, and ability to write efficient, correct low-level code. This round tests whether you can still execute at the coding level despite being a staff-level engineer.
Tips & Advice
Write clean, idiomatic C/C++ code with proper error handling. Show awareness of memory constraints, performance implications, and real-time considerations. Explain your thought process: consider cache behavior, memory alignment, and hardware access patterns. Don't over-engineer—solve the problem efficiently for the hardware constraints given. If provided a choice of language, stick with C or C++ unless the problem specifically calls for something else. Be comfortable discussing bit operations, struct packing, volatile qualifiers, and low-level optimization techniques.
Focus Topics
Real-time constraints and execution efficiency
Understanding timing constraints, avoiding unbounded operations, predictable execution, interrupt-safe code patterns
Practice Interview
Study Questions
Hardware register manipulation and bit operations
Reading/writing registers, bit shifting, masking, understanding volatile qualifiers, hardware access patterns
Practice Interview
Study Questions
C/C++ embedded systems coding
Writing efficient, correct embedded C/C++ code with attention to memory, performance, and hardware constraints
Practice Interview
Study Questions
Memory management and optimization
Stack vs. heap, memory alignment, cache efficiency, avoiding allocations in real-time code, static memory patterns
Practice Interview
Study Questions
Technical Phone Screen 2 - Embedded Systems Architecture & Design
What to Expect
Second technical phone interview focusing on higher-level embedded systems design thinking. You may be asked to design a simple embedded system (e.g., a sensor node, IoT device firmware structure, or hardware-software integration approach) or analyze trade-offs in an existing embedded architecture. This round evaluates your ability to think beyond individual code and consider system-level decisions, hardware constraints, power consumption, scalability, and communication protocols. Expect questions about firmware architecture, embedded software patterns, and integration with hardware.
Tips & Advice
Think about the entire system: hardware constraints (CPU speed, RAM, flash), communication requirements, power budget, and scalability. Ask clarifying questions about hardware specs, expected scale, and real-world deployment constraints. Discuss trade-offs explicitly (e.g., memory vs. speed, battery life vs. responsiveness). Mention specific embedded patterns: bootloaders, firmware update mechanisms, state machines for device control, interrupt-driven vs. polling approaches. For staff-level, show that you've designed systems at scale and understand the implications of architectural choices.
Focus Topics
Power consumption optimization
Sleep modes, active power management, battery-aware design, low-power communication strategies
Practice Interview
Study Questions
Firmware testing, debugging, and reliability
Unit testing strategies for embedded code, debugging hardware-software issues, firmware robustness and error handling
Practice Interview
Study Questions
Communication protocols and hardware interfaces
I2C, SPI, UART, CAN, Bluetooth Low Energy; understanding when to use each and how to implement/debug them
Practice Interview
Study Questions
Hardware-software integration and constraints
Understanding microcontroller capabilities, GPIO, peripherals, timing requirements, and how to map software to hardware
Practice Interview
Study Questions
Embedded systems architecture patterns
Firmware structure, state machines, interrupt-driven design, event loops, modular firmware organization
Practice Interview
Study Questions
Onsite Round 1 - Core Embedded Systems Coding
What to Expect
In-person or video technical interview (45-60 minutes) where you will solve a moderately complex embedded systems coding problem in C or C++. The problem may involve hardware simulation (e.g., a mock hardware interface you must interact with), real-time constraints, or multi-module integration. You will write working code on a whiteboard or shared editor, explaining your approach and handling edge cases. This round validates that you can execute under interview conditions and think clearly about embedded systems challenges.
Tips & Advice
Start by understanding the hardware model or constraints: ask about CPU speed, memory available, interrupt latency, and any real-world deployment details. Write code incrementally, validating your logic as you go. Handle edge cases explicitly. Discuss your assumptions about hardware behavior and error conditions. Show comfort with low-level debugging concepts (registers, memory layout, timing). Don't rush—clarity and correctness matter more than speed. Walk the interviewer through your code and be ready to discuss optimizations or alternative approaches.
Focus Topics
Error handling and edge case coverage
Handling hardware failures, timeouts, invalid states, and ensuring graceful degradation
Practice Interview
Study Questions
Hardware simulation and mock interface handling
Interacting with simulated hardware (registers, sensors, peripherals), writing testable embedded code
Practice Interview
Study Questions
State management in firmware
Designing state machines for device control, managing complex hardware states, handling transitions safely
Practice Interview
Study Questions
Interrupt handling and concurrency
Interrupt service routines, critical sections, volatile data, race conditions, and safe concurrent access patterns
Practice Interview
Study Questions
Onsite Round 2 - Embedded Systems Design & Architecture
What to Expect
In-person design interview (60 minutes) where you will design a moderately complex embedded system from scratch. You might be asked to design a simple IoT device, a firmware architecture for a household product, or a hardware-software system for a marketplace application. You will be evaluated on your ability to break down the problem, identify hardware constraints, propose a scalable architecture, discuss trade-offs, and think about long-term maintainability. Expect deep questioning about why you made specific choices and how you would handle scaling or failures.
Tips & Advice
Start by clarifying requirements and constraints: hardware capabilities, scale, power budget, reliability needs, update mechanisms, and time-to-market. Sketch out a high-level architecture with firmware layers, hardware interfaces, and communication paths. Discuss specific challenges (power management, update delivery, debugging in the field). Mention how you would test and verify the system. For staff-level, emphasize scalability: how would this design handle 10x more devices? How would you maintain it across a large fleet? Discuss your experience designing similar systems and lessons learned.
Focus Topics
Security and cryptography in embedded systems
Hardware-based security, secure boot, encrypted storage, authenticated updates, protection against tampering
Practice Interview
Study Questions
Firmware update and fleet management
Over-the-air updates, rollback strategies, version management, field debugging, safety in updates
Practice Interview
Study Questions
Scalability and fleet monitoring
Designing systems that can scale to thousands or millions of devices, telemetry, diagnostics, and remote management
Practice Interview
Study Questions
Hardware-software interface definition
Defining clear hardware abstraction layers, driver interfaces, and modularity for hardware independence
Practice Interview
Study Questions
Power management and resource optimization
Designing for battery life, managing CPU usage, memory efficiency, communication cost, thermal considerations
Practice Interview
Study Questions
Embedded system architecture from requirements
Translating hardware and business requirements into firmware architecture, module boundaries, and interfaces
Practice Interview
Study Questions
Onsite Round 3 - Performance Optimization and Debugging
What to Expect
In-person technical interview (60 minutes) focused on optimization and deep debugging skills. You may be presented with a firmware performance problem (e.g., too slow, high power consumption, memory issues) and asked to diagnose and optimize it. Or you may be asked to debug a complex hardware-software integration issue with a hardware simulator. This round evaluates your expertise in profiling, optimization, and real-world debugging—skills that differentiate senior and staff-level engineers.
Tips & Advice
When faced with a performance problem, start by understanding what 'performance' means: speed, latency, power, memory? Ask for metrics and constraints. Propose a systematic debugging approach: profiling, instrumentation, hypothesis testing. Show familiarity with embedded debugging tools (JTAG, logic analyzers, software profiling). Discuss trade-offs between different optimization strategies. Mention real-world examples where you've optimized embedded systems. For staff-level, emphasize your ability to mentor others in debugging and your strategic thinking about performance architecture.
Focus Topics
Real-time system analysis and latency optimization
Understanding interrupt latency, context switch costs, real-time scheduling, predictable execution
Practice Interview
Study Questions
Hardware debugging and instrumentation
Using JTAG debuggers, logic analyzers, hardware breakpoints, real-time tracing, bus monitoring
Practice Interview
Study Questions
CPU and memory optimization techniques
Register allocation, cache optimization, instruction scheduling, code size reduction, algorithm efficiency
Practice Interview
Study Questions
Profiling and performance measurement
Instrumenting embedded code, measuring CPU usage, timing, power consumption; tools and techniques for profiling
Practice Interview
Study Questions
Power optimization and battery-aware design
Reducing active power, sleep mode strategies, dynamic voltage and frequency scaling, power profiling
Practice Interview
Study Questions
Onsite Round 4 - Leadership, Mentorship, and Cross-Functional Collaboration
What to Expect
In-person behavioral and leadership interview (60 minutes) evaluating your ability to lead embedded systems initiatives, mentor junior and senior engineers, and work effectively with hardware teams and other disciplines. You will discuss past projects where you led architectural decisions, mentored engineers, resolved technical conflicts, or drove innovation. Airbnb values execution and practical problem-solving—expect questions about how you ship code, handle constraints, and collaborate with non-engineers (hardware designers, product managers, manufacturing). This round assesses staff-level leadership qualities.
Tips & Advice
Prepare 3-4 detailed stories demonstrating: (1) leading a complex embedded project end-to-end, (2) mentoring junior or senior engineers in embedded systems, (3) collaborating with hardware teams to solve a tricky integration problem, (4) driving architectural innovation or making a tough trade-off decision. Use the STAR method (Situation, Task, Action, Result) but emphasize the outcome and impact. Show humility—staff-level engineers admit mistakes and learn. Discuss how you handle pressure, ship code with constraints, and make decisions with incomplete information. Highlight cross-functional leadership: working with hardware engineers, product managers, manufacturing, and other teams. Mention your philosophy on code quality, mentorship, and continuous improvement.
Focus Topics
Technical decision-making and trade-offs
Making architectural choices with incomplete information, justifying decisions, handling disagreements, learning from failures
Practice Interview
Study Questions
Airbnb values alignment (bias to action, ownership, collaboration)
Demonstrating how you embody Airbnb's cultural values: making quick decisions, taking ownership, and collaborating effectively
Practice Interview
Study Questions
Execution under constraints and pressure
Shipping code with hardware limitations, time pressure, resource constraints; balancing perfection with delivery
Practice Interview
Study Questions
Mentorship and engineering growth
Teaching junior/senior engineers embedded concepts, code review practices, technical guidance, helping others grow into staff level
Practice Interview
Study Questions
Cross-functional collaboration with hardware engineers
Working with hardware teams to define interfaces, debug integration issues, influence hardware decisions from software perspective
Practice Interview
Study Questions
Leading complex embedded systems projects
Owning end-to-end firmware projects, managing timelines, coordinating with hardware teams, driving architecture decisions
Practice Interview
Study Questions
Onsite Round 5 - Culture Fit and Behavioral Assessment
What to Expect
In-person final interview (45-60 minutes) with a senior engineer or hiring manager focused on culture fit, problem-solving philosophy, and long-term career alignment. This round emphasizes Airbnb's core values: belonging, bias to action, optimism, adventure, and honest communication. You will discuss how you approach challenges, communicate with diverse teams, embrace Airbnb's mission, and see yourself growing at the company. This is an opportunity to show you're not just technically excellent but also a great teammate and leader.
Tips & Advice
Connect your experience to Airbnb's values. For example, discuss how you've taken bold action despite uncertainty (bias to action), owned outcomes even when they were hard (belonging and ownership), or embraced learning from failure. Be authentic—culture fit is about genuine alignment, not performative agreement. Discuss your curiosity about the travel and marketplace domain and how embedded systems might enhance guest or host experiences. Ask thoughtful questions about Airbnb's embedded systems roadmap, team structure, and how you'd grow as a staff engineer. Show that you're energized by the mission and want to contribute to Airbnb's long-term success.
Focus Topics
Long-term career vision and growth at Airbnb
Your vision for embedded systems at Airbnb, how you'd grow as a staff engineer, and your commitment to the company mission
Practice Interview
Study Questions
Communication and storytelling
Ability to explain complex technical concepts to non-technical audiences, inspire teams, and communicate vision
Practice Interview
Study Questions
Problem-solving philosophy and intellectual curiosity
How you approach novel problems, learn new domains, embrace ambiguity, and stay current with embedded systems trends
Practice Interview
Study Questions
Airbnb core values alignment (belonging, bias to action, optimism)
Demonstrating authentic alignment with Airbnb's cultural values through examples and philosophy
Practice Interview
Study Questions
Frequently Asked Embedded Developer Interview Questions
Given a linker map showing stack at the top of RAM and a large BSS near that region, describe how to interpret the map to compute the safe stack margin. Explain how to adjust the linker script or move large buffers to external RAM or heap, and how to reserve a red zone to detect stack overflow.
Sample Answer
Read the map and compute safe stack margin
- Find the top-of-RAM symbol (often _estack or __StackTop) and the end of BSS (.bss end symbol like _ebss or bss_end).
- Stack grows downward, so safe margin = (stack_start_address) - (highest_address_used_by_bss_or_static) - safety_reserve.
- Example: Stack start 0x20010000, _ebss = 0x2000F200 → raw free = 0xE00 (3584 bytes). Choose safety_reserve (guard + scheduler/interrupt worst-case) and subtract to get usable stack.
Adjust linker script or move large buffers
- Move large buffers to external RAM region in linker script:
.ext_ram (NOLOAD) : {
.ext_bss_start = .;
*(.ext_bss)
.ext_bss_end = .;
} > EXT_RAM
- In C:
uint8_t big_buf[64*1024] __attribute__((section(".ext_bss")));
- Or allocate on heap at init (malloc) if runtime placement acceptable. Or mark as dynamically allocated to avoid static BSS.
Reserve a red zone / stack canary
- Add a dedicated region between .bss and stack in linker script with a fill pattern:
.stack_guard_start = .;
.stack_guard = . + 1024; /* 1KB red zone */
.fill 0xDEADBEEF
- Or fill with known pattern at boot and check periodically/at context switch; or place a canary at stack base and verify on ISR/ task switch to detect overflow.
Practical tips
- Re-scan map after builds; identify largest static objects.
- Use smaller stacks for idle tasks; measure actual stack usage with fill-pattern runtime profiling.
- When moving buffers to external RAM, verify startup initialization (.data copy, zero .bss) covers external region or initialize manually.
Walk me through a time you coached someone whose performance was genuinely below the bar. How did you approach the conversations, and how did it turn out?
Sample Answer
Direct answer
Coaching a genuine underperformer starts with diagnosing why (skill gap, unclear expectations, motivation, or something outside work like a health or personal issue) before assuming it's a will problem, then moving to a private, honest conversation with specific examples, a written and time-bound improvement plan with objective checkpoints, and a clear, stated understanding of what happens if the bar still isn't met. The hard part isn't the first conversation, it's staying honest and consistent through every checkpoint after it.
Structured elaboration
Diagnose before you coach
Below-the-bar performance has different root causes that call for different responses:
- Skill gap: they don't yet know how to do the thing. Response: targeted teaching, pairing, smaller scoped tasks.
- Unclear expectations: they don't know what "good" looks like here. Response: make the bar explicit and concrete, with examples.
- Motivation or engagement: they can do it but aren't. Response: a more direct conversation about what's changed and why.
- Something outside work: a health issue, a personal crisis, burnout. A private, non-judgmental check-in on wellbeing belongs early in this process, both because it's the right thing to do and because it changes what the right intervention is (support and possibly a formal accommodation, not a performance plan).
Getting this wrong (coaching a skill gap like it's a motivation problem, or the reverse) wastes the improvement window on the wrong intervention.
The conversation and the plan
- Deliver the message privately, plainly, and with specific examples: what's below the bar, what the bar actually is, and why it matters.
- Put the plan in writing: two or three concrete, observable goals, a defined timeframe, and what evidence would count as "met."
- Set a regular check-in cadence shorter than your normal 1:1 rhythm; below-the-bar performance needs tighter feedback loops, not the same cadence as everyone else.
When to involve HR formally
This is a judgment call many candidates get wrong by either never mentioning HR (naive) or looping HR in immediately (overcautious, and it can undermine trust). A reasonable line: loop in HR or your manager as soon as the conversation could plausibly lead to a formal employment outcome (a documented warning, or separation), even if you're optimistic it won't get there, because that's exactly when documentation and process need to be right from the start rather than reconstructed after the fact.
Protecting the team
The rest of the team usually already knows something is off; silence reads as either denial or unfairness. Without disclosing private performance details, it's reasonable to acknowledge you're aware of the gap and are addressing it, and to be transparent about redistributing work if needed, so the team doesn't quietly conclude the issue is being ignored.
Worked example
Situation
An engineer on a team I was supporting had been reliably strong for over a year, then their output quality and delivery reliability dropped off sharply over a couple of months: reviews were taking longer, deadlines were slipping, and the pattern didn't match a normal bad sprint.
Diagnosis
Before assuming a motivation problem, I had a private, low-pressure conversation focused on checking in rather than accusing. That surfaced that part of the issue was a skill gap on a newer part of the codebase they'd been assigned to without much ramp-up, but there was also something going on outside work affecting their focus.
Action
We set a short, explicit improvement plan: two concrete, observable goals tied to real upcoming work, a shorter check-in cadence, and pairing time on the unfamiliar codebase area. I also made sure they knew about the option to talk to HR about support resources for the personal situation, kept separate from the performance conversation so the two didn't get conflated.
Result
Performance recovered within the plan's window once the skill gap closed and the external situation stabilized. Because the conversation started from genuine diagnosis rather than an assumption, the plan addressed the actual cause instead of just adding pressure, and the person stayed on the team and rebuilt trust with the group.
The other branch (when it doesn't turn around)
Not every case ends this way. When someone doesn't meet a documented plan's criteria despite real support, the path is a harder, well-documented conversation, formal HR involvement, and eventually separation if there's no path forward. The mentor's job at that point shifts from "close the gap" to making sure the process is fair, well-documented, and handled with dignity, and to being honest with the rest of the team (without violating privacy) that a change is coming so it doesn't land as a surprise.
Trade-offs & pitfalls
- Treating every case as a motivation problem. The single biggest junior mistake here is skipping diagnosis and going straight to "try harder" messaging, which fails skill-gap and external-cause cases and can be actively harmful if there's something like burnout or a health issue underneath.
- Involving HR too late (or too early). Too late, and you've lost the documentation trail that protects everyone, including the underperformer, if it does become formal. Too early or too visibly, and it can read as punitive before the person's had a real chance, damaging trust unnecessarily.
- Optimizing for the individual at the team's expense, or the reverse. A senior answer holds both: real support for the person, and honesty with the team about workload and timeline impact, rather than pretending nothing's happening.
- No exit criteria stated up front. A plan without a clear "what does not-met look like, and what happens then" isn't actually a plan, it's a delay, and it's unfair to the person because they don't know what they're actually being measured against.
You were passed over for a promotion you expected, or your growth has stalled for reasons outside your control (budget freeze, reorg, unclear criteria). Walk me through how you'd diagnose what actually happened and what your next two quarters would look like.
Sample Answer
Direct answer
Before building any recovery plan, diagnose the actual cause: a genuine readiness gap, ambiguous or inconsistently applied criteria, or a structural block (budget freeze, reorg) entirely outside your control, since the right two-quarter plan looks completely different depending on which one it is.
Structured elaboration
- Diagnose before acting, this is the step several answers skip. Ask directly, your manager and, if appropriate, a skip-level or HR (human resources), which bucket this falls into. The same discipline applies whether the specific situation is being passed over for promotion twice in a row, an HR or budget block despite clear manager support, mixed and inconsistent promotion-review feedback, or your team being disbanded in a reorg with nothing to do with your performance.
- Get the diagnosis in writing where you can (a short recap email after the conversation), so the criteria for next time are explicit and can't quietly drift again.
- Match the two-quarter plan to the diagnosis: a readiness gap calls for naming the one or two specific gaps and a concrete way to close them; ambiguous criteria call for pushing for a written, specific bar and calibrating against a recently promoted peer; a structural block calls for negotiating interim recognition (scope, title, or a compensation alternative) and simply continuing to deliver visibly, since the case itself doesn't need rebuilding.
- Keep a running log of impact regardless of cause, so the next review relies on a record rather than memory.
Worked example
I expected a promotion and didn't get it, and my first move wasn't a recovery plan, it was asking my manager directly what had actually driven the decision. It turned out to be a mix: the committee felt the case was strong on delivery but thin on evidence of cross-team impact, and separately, headcount for that level was frozen that cycle regardless of anyone's case. Knowing both halves changed what I did next. For the readiness half, I picked one initiative deliberately structured to touch two other teams and documented it as I went rather than after the fact. For the frozen-headcount half, I didn't spend energy trying to fix something outside my control, I asked for an interim scope change I could point to later and kept the impact log running so the next review had a record instead of the same ambiguous case.
Trade-offs & pitfalls
- The most common mistake is skipping the diagnosis and jumping straight into a remediation plan; if the real cause was budget, the plan solves the wrong problem and burns two quarters proving something nobody doubted.
- Accepting a vague answer ("just not quite there yet") instead of pushing for specifics sets up the same ambiguous outcome next cycle.
- Asking for interim recognition (title, scope) before you understand the real cause can read as entitled; sequence it after the diagnosis.
- Nursing a private grievance instead of a calibrated, written understanding of the criteria repeats the cycle.
Implement a minimal SPI transfer routine in C for an MCU without DMA: the routine should send N bytes and receive N bytes full-duplex. Show how you would handle variable SPI clock speeds and switching modes safely when multiple devices share the peripheral. Discuss interrupt vs polling trade-offs for this implementation.
Sample Answer
Approach (brief)
Provide a safe, minimal blocking full-duplex SPI transfer: assert CS, configure mode/clock if changed, transfer N bytes by writing TXDR then waiting for RXDR, finally deassert CS. Support variable clock by reconfiguring baud register before asserting CS and protect shared peripheral with a mutex/lock.
Code (blocking, polling)
// Example minimal SPI transfer (polling) for MCU with registers SPI->CR, SPI->DR, SPI->SR
#include <stdint.h>
typedef enum { SPI_MODE0=0, SPI_MODE1, SPI_MODE2, SPI_MODE3 } spi_mode_t;
volatile uint32_t LOCK=0;
static inline void lock_acquire(void){ while(__atomic_test_and_set(&LOCK, __ATOMIC_ACQUIRE)); }
static inline void lock_release(void){ __atomic_clear(&LOCK, __ATOMIC_RELEASE); }
int spi_transfer(uint8_t *tx, uint8_t *rx, size_t n, uint32_t baud_div, spi_mode_t mode, void (*cs_assert)(int), void (*cs_deassert)(int), int dev_id){
lock_acquire();
// safe reconfigure
SPI->CR &= ~SPI_CR_ENABLE;
SPI->BR = baud_div; // set clock
SPI->CR = (SPI->CR & ~SPI_CR_MODE_MASK) | (mode << SPI_CR_MODE_SHIFT);
SPI->CR |= SPI_CR_ENABLE;
cs_assert(dev_id);
for(size_t i=0;i<n;i++){
SPI->DR = tx ? tx[i] : 0xFF; // write to start transfer
while(!(SPI->SR & SPI_SR_RXNE)); // poll RX ready
uint8_t r = (uint8_t)SPI->DR;
if(rx) rx[i]=r;
}
cs_deassert(dev_id);
lock_release();
return 0;
}
Interrupt vs Polling (trade-offs)
- Polling: simple, deterministic latency, good for short bursts and bare-metal; wastes CPU if transfers long.
- Interrupt-driven: lower CPU usage, better for multitasking or long transfers; more complex (state machine, circular buffers), higher ISR overhead and latency jitter.
- Choose polling for < few hundred bytes or realtime-critical inner loops; choose interrupts (or DMA) when offloading CPU and handling concurrent tasks.
Edge cases / safety
- Ensure CS asserted before transfers and deasserted after last byte (clocking).
- Protect config changes with a lock or run in critical section.
- Handle FIFO/full/overrun flags and timeouts in production code.
Write a small C function that reports whether the host is little-endian, and one that converts a 32-bit value to big-endian. What portability and strict-aliasing pitfalls should you avoid, and what bugs appear when code assumes host byte order matches the data format?
Sample Answer
Direct answer. Endianness is the order in which the bytes of a multi-byte number sit in memory: little-endian stores the least significant byte first (x86-64 and most ARM systems), big-endian stores it last (network byte order, the big-endian order that internet protocols use for numbers on the wire, and many file formats). To test the host, store a known value such as 1 and look at its first byte through a character type or memcpy. To convert a 32-bit value to big-endian, either swap bytes arithmetically or, better for parsing, build and take apart values with shifts at fixed byte positions, which is correct on every host. The pitfalls are casting a char * or packet buffer to uint32_t * (a strict-aliasing violation and a possible misaligned access, both undefined behaviour) and treating the packet's byte order as the host's byte order.
The two functions, plus the parsing helpers
#include <stdalign.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* Runtime check: inspect the first byte of a known value through memcpy. */
static int host_is_little_endian(void) {
const uint16_t one = 1;
unsigned char first;
memcpy(&first, &one, 1);
return first == 1;
}
/* Reverse the byte order of a value. Pure arithmetic, so it behaves the same on every host. */
static uint32_t swap32(uint32_t v) {
return ((v & 0x000000FFu) << 24) | ((v & 0x0000FF00u) << 8) |
((v & 0x00FF0000u) >> 8) | ((v & 0xFF000000u) >> 24);
}
/* Host value -> value whose in-memory bytes are big-endian: swap on a little-endian host, identity on a big-endian one. */
static uint32_t host_to_be32(uint32_t v) {
return host_is_little_endian() ? swap32(v) : v;
}
/* Wire fields: byte positions are fixed by the format, so host order never matters. */
static uint32_t load_be32(const unsigned char *p) {
return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | (uint32_t)p[3];
}
static void store_be32(unsigned char *p, uint32_t v) {
p[0] = (unsigned char)(v >> 24); p[1] = (unsigned char)(v >> 16);
p[2] = (unsigned char)(v >> 8); p[3] = (unsigned char)v;
}
static uint32_t load_le32(const unsigned char *p) {
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
/* The tempting wrong way: reinterpret packet bytes as a uint32_t. */
static uint32_t bad_load_be32(const unsigned char *p) {
return *(const uint32_t *)p;
}
int main(void) {
printf("host is little-endian: %d\n", host_is_little_endian());
uint32_t be = host_to_be32(0x11223344u);
unsigned char mem[4];
memcpy(mem, &be, 4);
printf("host_to_be32(0x11223344) = 0x%08x, bytes in memory: %02x %02x %02x %02x\n", be, mem[0], mem[1], mem[2], mem[3]);
alignas(4) unsigned char pkt[12] = {0xFF, 0, 0, 0, 0x10, 0, 0, 0, 0, 0, 0, 0x2A};
printf("load_be32(pkt+1) = %u (bytes 00 00 00 10, expect 16)\n", load_be32(pkt + 1));
printf("load_le32(pkt+1) = %u (same bytes read little-endian)\n", load_le32(pkt + 1));
printf("load_be32(pkt+8) = %u (bytes 00 00 00 2a, expect 42)\n", load_be32(pkt + 8));
printf("bad_load_be32(pkt+8) = %u (aligned, but host order)\n", bad_load_be32(pkt + 8));
unsigned char out[4];
store_be32(out, 0x11223344u);
printf("store_be32 bytes: %02x %02x %02x %02x\n", out[0], out[1], out[2], out[3]);
printf("bad_load_be32(pkt+1) = %u (misaligned read)\n", bad_load_be32(pkt + 1));
return 0;
}
Built and run in a Linux container (GCC 14.4, aarch64 little-endian host) with gcc -O2 -Wall -Wextra -fsanitize=address,undefined endian.c -o endian && ./endian:
endian.c:39:12: runtime error: load of misaligned address 0xffff90800041 for type 'const uint32_t', which requires 4 byte alignment
host is little-endian: 1
host_to_be32(0x11223344) = 0x44332211, bytes in memory: 11 22 33 44
load_be32(pkt+1) = 16 (bytes 00 00 00 10, expect 16)
load_le32(pkt+1) = 268435456 (same bytes read little-endian)
load_be32(pkt+8) = 42 (bytes 00 00 00 2a, expect 42)
bad_load_be32(pkt+8) = 704643072 (aligned, but host order)
store_be32 bytes: 11 22 33 44
bad_load_be32(pkt+1) = 268435456 (misaligned read)
(The first line is UBSan's message on stderr, so it appears before the buffered output; the 0xffff... address differs between runs. UBSan also prints a note: pointer points here line and a byte dump after that message, omitted here.) The same source compiled and run on a big-endian machine (an s390x Alpine container, s390x being a big-endian IBM mainframe CPU, run under QEMU, a CPU emulator, gcc -O2 -Wall -Wextra endian.c -o endians) printed:
host is little-endian: 0
host_to_be32(0x11223344) = 0x11223344, bytes in memory: 11 22 33 44
load_be32(pkt+1) = 16 (bytes 00 00 00 10, expect 16)
load_le32(pkt+1) = 268435456 (same bytes read little-endian)
load_be32(pkt+8) = 42 (bytes 00 00 00 2a, expect 42)
bad_load_be32(pkt+8) = 42 (aligned, but host order)
store_be32 bytes: 11 22 33 44
bad_load_be32(pkt+1) = 16 (misaligned read)
Reading the little-endian run: host_to_be32 swapped the bytes of 0x11223344, so the integer it returned prints as 0x44332211, but what matters is the memory behind it. A little-endian CPU stores the least significant byte first, so the integer 0x44332211 sits in memory as 11 22 33 44, which is the big-endian layout of the original number. That is why the printed integer looks "wrong" while the bytes are right. On the big-endian machine the value was already in that order, so nothing was swapped and it printed 0x11223344 with the same bytes. The load_be32, store_be32 and the in-memory bytes of host_to_be32 are identical on both machines, which is the point: they describe the format. bad_load_be32 gives 42 on the big-endian host and 704643072 on the little-endian one, so code using it passes on one machine and breaks on the other.
Reasoning through the pitfalls
- Why
host_to_be32must check the host. The byte swapswap32is pure arithmetic and always reverses the bytes. On a big-endian host the value is already in big-endian order, so the conversion must do nothing, and a function that always swaps is wrong there. In practice callhtonl(<arpa/inet.h>, POSIX; "host to network long": converts a 32-bit value from host order to big-endian network order), or on GCC/Clang__builtin_bswap32(a compiler built-in that reverses the four bytes) guarded by the compiler's byte-order macro, and let the library handle the host difference. - Strict aliasing. C lets the compiler assume that an object of one type is not accessed through a pointer to an unrelated type (the strict-aliasing rule; character types are the exception).
*(const uint32_t *)pon a byte buffer breaks that rule. Usememcpyinto auint32_t(compilers turn it into one load) or build the value with shifts; both are valid in C and C++. - Alignment. A
uint32_t *pointing at an odd address is misaligned: UBSan flagged thepkt+1read above, and some CPUs fault on it. Parsing with byte loads has no alignment requirement. - Shifting signed values. Shift unsigned operands, and cast each byte to
uint32_tbefore<<(auint8_tpromotes to a signedint: for the byte0x80,0x80 << 24is0x80000000, which does not fit in a signed 32-bitintwhose maximum is0x7FFFFFFF, and in C that overflow in a shift is undefined). - Compiler quality. The shift-and-or
load_be32compiles at-O2toldr w0, [x0]plusrev w0, w0(AArch64: load four bytes, then reverse their order) andmovl (%rdi), %eaxplusbswap %eax(x86-64: the same pair, load then byte-reverse), so the portable code costs no more than the cast.
Bugs that appear when host order is assumed
Parsing a network packet or a file header by overlaying a struct or casting works on the developer's little-endian laptop only if the format happens to be little-endian. Typical failures: a TCP port or a length field read byte-reversed (80 reads as 20480, 0x50 swapped to 0x5000); a magic number that matches on one build and never on another; a loop that trusts a byte-reversed length and over-reads (a security bug, since an attacker chooses the bytes); a file written on one CPU and unreadable on another. The defence is the rule in the code: say the byte order in the format specification, read and write each field with explicit byte positions, and test on a big-endian target (an emulator is enough).
Trade-offs
Use the portable shift form by default. Reach for memcpy plus a swap when profiling shows the byte-wise form matters on a compiler that does not recognize the pattern, and for bulk data convert in a loop the compiler can vectorize (compile into instructions that handle several values at once). Do not gate behaviour on a runtime endianness probe in hot paths: it is constant for a build, so use compile-time macros there.
Explain chunked downloads with resume support for firmware transfers in intermittent networks. Describe how to track progress on device, how to verify each chunk, how to minimize RAM usage while assembling the image to flash, and how to safely resume after power or connectivity loss.
Sample Answer
Approach overview
Chunked download + resume means fetching the firmware in fixed-size blocks (e.g., 4–64 KiB) using HTTP Range or a custom protocol, verifying each block, storing progress persistently, and assembling/writing to flash with minimal RAM until fully validated and activated.
Tracking progress on device
- Persist a small download state in non-volatile storage (EEPROM/flash metadata): total size, chunk size, last-successful-chunk-index, and a compact bitmap or small vector of received-chunk flags.
- On boot/resume, read this metadata to know which ranges remain. Use sequence numbers to avoid races.
Verifying each chunk
- Server provides per-chunk integrity (SHA256 or CRC32) or a Merkle tree root; each chunk carries its hash.
- After receiving a chunk, compute its hash incrementally (streaming) and compare before committing to flash.
- For extra security, sign the final image and verify signature in bootloader.
Minimizing RAM while assembling
- Stream-write chunks directly to a staging flash area or secondary bank rather than buffering full image in RAM.
- Use a single small receive buffer (e.g., 4–8 KiB), verify, then write via flash driver/DMA. Keep only hash state in RAM.
- Align writes to flash page sizes; avoid whole-image copies by using two-bank (A/B) firmware scheme.
Safe resume after power/connectivity loss
- Make chunk writes and metadata updates atomic: write chunk → verify → flush cache → update bitmap and last-successful-chunk in persistent metadata.
- Use wear-friendly journaling: write new metadata record then mark old as invalid (or use checksumed ring).
- Bootloader should only switch to new image after full integrity and signature verification; if interrupted, it falls back to known-good bank.
Notes / trade-offs
- Smaller chunks improve resume granularity but add overhead; pick chunk size considering MTU, flash write cost, and hash compute cost.
- Use CRC32 for speed on constrained MCUs, SHA256 for stronger security (hardware accel if available).
A battery-powered sensor node must fit its flash and still meet its timing. How would you choose and validate compiler optimisation settings, including what you would switch off for a C++ codebase, and how do you spot the bugs that only show up when optimisation changes?
Sample Answer
Recommendation. Ship at -Os with -ffunction-sections -fdata-sections and the linker flag -Wl,--gc-sections, put only a measured hot path at -O2 (by compiling that one source file with different flags in the build system), switch off the C++ features you do not use, and validate by building the shipped configuration in CI and running the tests and the timing measurements at that level. Do not test at -O0 and ship at -Os: they are different programs as far as undefined behaviour is concerned.
1. Choose from measured numbers, not folklore. The sample C file below has three typical firmware workloads, so the size comparison covers different code shapes: a bitwise CRC (a checksum computed one bit at a time: shift right, and XOR in the polynomial 0xEDB88320 whenever the bit shifted out was 1; -(int32_t)(crc & 1u) builds an all-ones or all-zero mask from that bit), an 8-tap fixed-point filter (eight multiply-accumulate steps; Q15 means each coefficient is a 16-bit integer with 15 fractional bits, so 32768 would stand for 1.0 (the largest 16-bit value, 32767, is just under it), and acc >> 15 rescales the result) and a small state machine (a switch that picks the next state from the current state and an event).
#include <stdint.h>
#include <stddef.h>
uint32_t crc32_update(uint32_t crc, const uint8_t *p, size_t n)
{
while (n--) {
crc ^= *p++;
for (int b = 0; b < 8; b++)
crc = (crc >> 1) ^ (0xEDB88320u & (uint32_t)-(int32_t)(crc & 1u));
}
return crc;
}
int16_t fir8(const int16_t *x, const int16_t *h) /* 8-tap filter, Q15 coefficients */
{
int32_t acc = 0;
for (int i = 0; i < 8; i++) acc += (int32_t)x[i] * h[i];
return (int16_t)(acc >> 15);
}
typedef enum { IDLE, SAMPLING, SENDING } state_t;
state_t step(state_t s, int ev)
{
switch (s) {
case IDLE: return ev == 1 ? SAMPLING : IDLE;
case SAMPLING: return ev == 2 ? SENDING : SAMPLING;
default: return ev == 3 ? IDLE : SENDING;
}
}
Compiled for Cortex-M4 with arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb <level> -ffunction-sections -c app.c in a gcc:14 container (arm-none-eabi-gcc 14.2.1), the code size in bytes (the text column of arm-none-eabi-size app.o) was:
-O0 254
-O1 118
-O2 124
-O3 228
-Os 102
-Os is smallest, -O1 and -O2 are close, -O3 is nearly twice -O2 (228 against 124 bytes), the kind of growth that more aggressive unrolling and inlining produce, and -O0 is the largest. This is one sample on one toolchain version: size and speed move with the core, compiler version and code, so run the same comparison on your own code. For a flash-limited part, start at -Os and measure what the timing budget needs. For battery life, do not assume the smaller build uses less energy: a faster build can finish sooner and let the part sleep sooner, so measure the node's energy per measurement cycle for the candidate levels. Time with the core's cycle counter (a hardware register that counts CPU clock cycles) or a pin toggled and captured on a logic analyzer (an instrument that records digital signals against time).
2. Linker-level size savings that cost no speed. -ffunction-sections -fdata-sections puts each function and variable in its own section, and -Wl,--gc-sections lets the linker drop every section nothing references. The map file lists what was discarded, so you can see what a library dragged in. Link-time optimisation (-flto, which lets the optimiser see all source files at once at link time) can shrink further by inlining across files, but it makes bugs harder to localise, so enable it as a separate, tested step.
3. What to switch off for a C++ codebase. The second sample has a class with a destructor (cleanup that must run if may_throw throws, the pattern called RAII: resource cleanup tied to an object's lifetime) and a function-local static object with a constructor.
extern void may_throw(int);
extern void log_msg(const char *);
struct Guard { /* RAII object: needs cleanup if may_throw() throws */
~Guard() { log_msg("done"); }
};
void work(int x)
{
Guard g;
may_throw(x);
}
struct Config { Config() { log_msg("init"); } int v = 3; };
int cfg_value(void)
{
static Config c; /* function-local static with a constructor */
return c.v;
}
Compiled with arm-none-eabi-g++ -mcpu=cortex-m4 -mthumb -Os -c, the non-empty sections that arm-none-eabi-size -A listed for the object file with default C++ flags (the header line, the Total line and the .comment and .ARM.attributes rows are left out, and the same omissions apply to the second listing) were:
.text 88 0
.bss 8 0
.rodata.str1.1 10 0
.ARM.extab 44 0
.ARM.exidx 16 0
and with -fno-exceptions -fno-rtti -fno-threadsafe-statics:
.text 56 0
.bss 8 0
.rodata.str1.1 10 0
The unwind tables (.ARM.extab and .ARM.exidx, 60 bytes here: the data the runtime uses to find and run destructors while an exception travels up the call stack) disappear and the code shrinks from 88 to 56 bytes, even in a file this small. The compiler wraps a function-local static in a static-initialisation guard (a hidden flag plus calls that make sure it is constructed exactly once, even if two threads arrive together). Counting the calls to the guard functions (__cxa_guard_acquire, __cxa_guard_release and __cxa_guard_abort) in the generated assembly (-S) gave the following. The guard flag variable itself stays in .bss; only the calls go away:
__cxa_guard calls with default flags: 3
__cxa_guard calls with -fno-threadsafe-statics: 0
Each flag has a condition.
-fno-exceptions: code that usestryorthrowno longer compiles, and libraries that report errors by exceptions need an alternative. Use it when error handling is return codes or asserts, which is the usual firmware style.-fno-rtti: removes run-time type information (RTTI), sodynamic_cast(a checked cast between class types) andtypeid(asks an object for its type) are unavailable. Virtual functions still work.-fno-threadsafe-statics: removes the guard calls around function-local statics. This is safe only if the first call of each such function happens in a single context, for example before the scheduler starts or before interrupts are enabled. If two tasks can race on first use, keep the guards and supply the runtime hooks, or initialise the object explicitly at startup.
Also keep heavyweight library parts (iostreams, anything that pulls innewanddeletethrough the heap) out of the image, and use the map file to confirm they are absent.
4. How to spot bugs that appear only when optimisation changes. The usual causes are undefined behaviour the compiler exploited, missing volatile, uninitialised variables, and timing assumptions. Undefined behaviour (UB) means the C standard puts no requirement on what a program does once it breaks certain rules. The compiler is allowed to assume the program never breaks them and to optimise on that assumption, so the result can differ between optimisation levels. Two such rules matter here. Signed overflow: adding to a signed int past INT_MAX is UB, so the compiler may assume it never happens. Strict aliasing: reading or writing an object through a pointer of an unrelated type is UB, so the compiler may assume an int * and a short * never point at the same memory. The sample program below has two such bugs. will_overflow tests for signed overflow with a + 1 < a, and alias writes an int and a short through pointers to the same object.
#include <stdio.h>
#include <limits.h>
__attribute__((noinline)) int will_overflow(int a)
{
return a + 1 < a; /* intended as an overflow test; signed overflow is undefined */
}
__attribute__((noinline)) int alias(int *i, short *s)
{
*i = 1;
*s = 2; /* writes through a different type to the same object */
return *i;
}
int main(void)
{
volatile int big = INT_MAX;
printf("will_overflow(INT_MAX) = %d\n", will_overflow(big));
union { int i; short s; } u;
printf("alias(...) = %d\n", alias(&u.i, &u.s));
return 0;
}
Compiled and run in the gcc:14 container (GCC 14.4.0, aarch64) at four settings with the script for o in -O0 -O2 "-O2 -fno-strict-aliasing -fwrapv" "-O2 -fsanitize=undefined"; do echo "== gcc $o"; gcc $o -Wall -Wextra optbug.c -o optbug; ./optbug; done, it printed:
== gcc -O0
will_overflow(INT_MAX) = 0
alias(...) = 2
== gcc -O2
will_overflow(INT_MAX) = 0
alias(...) = 1
== gcc -O2 -fno-strict-aliasing -fwrapv
will_overflow(INT_MAX) = 1
alias(...) = 2
== gcc -O2 -fsanitize=undefined
optbug.c:6:14: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
will_overflow(INT_MAX) = 1
alias(...) = 1
Why the outputs differ. In alias, the compiler assumes the short store cannot have changed the int, so at -O2 it returns the constant 1 it just stored instead of reloading *i. The aarch64 assembly from gcc -O2 -S (assembler directives removed, // comments added) shows it:
will_overflow:
mov w0, 0 // a + 1 < a is assumed never true, so the result is 0
ret
alias:
mov x3, x0
mov w0, 1 // the return value is the constant 1
mov w2, 2
str w0, [x3] // store 1 through the int pointer
strh w2, [x1] // store 2 through the short pointer; no reload of *i
ret
In will_overflow, a + 1 < a can only be true if a + 1 wrapped around, which the compiler assumes cannot happen, so it replaces the whole test with 0 and the INT_MAX input never gets a chance to wrap. -fwrapv tells the compiler that signed overflow wraps (two's complement), which makes the test meaningful again, and -fno-strict-aliasing turns off the aliasing assumption. Under -fsanitize=undefined the add is instrumented and really executed, so the test sees the wrapped value and returns 1 while the runtime reports the overflow; the sanitizer does not check aliasing, so alias still returns 1.
Two lessons. First, the aliasing bug changes result between -O0 (2) and -O2 (1), which is the "works in debug, fails in release" pattern; -fno-strict-aliasing restores the intended answer but the code is still wrong, and the fix is to access the object through one type or use memcpy. Second, the signed-overflow test returned 0 at both -O0 and -O2 here, so it was broken at every level, and only the sanitizer (which reports the overflow) and -fwrapv (which makes signed overflow wrap) revealed it. A test that merely passes at one level proves little.
A working routine for catching these:
- Build all host-testable logic at
-O0and at the shipped level, run the same tests on both, and diff the outputs. - Run the host tests under
-fsanitize=undefined,address(and-Wall -Wextra; the uninitialised-variable warnings need optimisation enabled to analyse the code). - For ISR-shared variables and registers, check
volatileand use the generated assembly (for example, the disassembly of a loop that polls a flag, to see whether the load was hoisted out of the loop) when a hang appears only in release. - Never time a delay with an empty loop: the optimiser may delete it. Use a hardware timer.
- Re-measure stack usage (
-fstack-usage) and timing at the shipped level, because inlining changes both. - When a release-only bug appears, bisect: change the level of one source file at a time until the failing file is known, then read its assembly.
-Og(the optimisation level designed to keep code debuggable) is a good intermediate for stepping through the code.
You are implementing a high-performance financial aggregation in C++ that sums millions of int64 values. Describe strategies to avoid overflow and preserve precision over large sums: a wider accumulator, periodic reduction, compensated summation (Kahan summation), and a big-integer fallback. Discuss the performance-versus-correctness trade-offs of each.
Sample Answer
Direct answer
Summing millions of floating-point values with a naive running total accumulates rounding error that grows with the number of additions, and can become catastrophically wrong once the accumulator itself becomes large relative to the individual values being added; Kahan summation tracks and corrects for the specific rounding error lost at each step, recovering close to exact precision at a small, constant extra cost per addition.
Structured elaboration
Why naive summation degrades. Each floating-point addition rounds its result to the nearest representable value; when the running total is already large and you add a comparatively small value, the low-order bits of that small value can be entirely lost in the rounding, contributing nothing to the total even though mathematically it should. Summed over millions of additions, this isn't a one-time rounding of the final answer, it's a compounding loss that grows with the number of terms and with how large the accumulator becomes relative to the values still being added.
A wider accumulator (e.g., summing into a double when inputs are float, or an extended-precision type). This delays the point at which the accumulator becomes "too large relative to the next value" by giving more bits of precision to work with, but does not eliminate the underlying problem, only pushes it further out; for a genuinely large enough sum, even a wider accumulator eventually exhibits the same degradation.
Periodic reduction (pairwise/hierarchical summation). Rather than one long running total, sum values in a tree (pairs, then pairs of pairs, and so on): this keeps each individual addition's two operands closer in magnitude to each other for longer, which is specifically what limits how much low-order precision gets lost at each step, and is a common approach in numerical libraries for exactly this reason.
Kahan (compensated) summation. Maintains a separate "compensation" value tracking the error lost in each addition's rounding, and feeds that error back into the NEXT addition to correct for it; this recovers close to exact precision using only a small, fixed amount of extra arithmetic per addition (a few extra operations per element), regardless of how many elements there are, which makes it strictly better than a wider accumulator alone for a sum where this class of error genuinely matters.
Big-integer fallback. For a sum where inputs are actually fixed-point or integer-representable quantities (a financial ledger's cent amounts, for instance) rather than genuinely continuous floating-point measurements, the more robust fix is often to avoid floating point ENTIRELY and sum as integers or a fixed-point/decimal type, sidestepping the rounding-error problem altogether rather than mitigating it.
Performance versus correctness. Kahan summation costs roughly four floating-point operations per element instead of one, a real but usually acceptable overhead for a batch aggregation that runs periodically rather than in an extremely tight, latency-critical hot loop; for a genuinely latency-critical inner loop where this precision doesn't actually matter to the business outcome, plain summation with a wider accumulator may be an acceptable, cheaper trade.
Worked example
double kahan_sum(const std::vector<double>& xs) {
double sum = 0.0, c = 0.0;
for (double x : xs) {
double y = x - c;
double t = sum + y;
c = (t - sum) - y;
sum = t;
}
return sum;
}
Executed and verified (g++, deliberately adversarial test case): summing a vector containing one value of 1.0e16, followed by 100,000 individual values of 1.0, followed by -1.0e16 (a true mathematical total of exactly 100,000.0). Naive left-to-right summation produced 0 (the individual 1.0 additions were entirely lost against the 1.0e16 accumulator before the final subtraction, since each 1.0 addition rounds to no change at all against a value that large). Kahan summation, on the SAME input, produced exactly 100000, matching the true mathematical answer with zero measured error, against the naive approach's error of 100000 (its full expected value, since it produced 0 instead). This is a deliberately extreme case constructed to make the effect visible and unambiguous; real financial aggregations rarely hit this exact pathological shape, but the same directional bias (naive summation systematically losing low-order precision as the accumulator grows) is present at a smaller, harder-to-notice scale in any large real sum, which is precisely what makes it dangerous: it degrades silently rather than producing an obviously-wrong number.
Trade-offs and pitfalls
The naive-versus-Kahan comparison above is deliberately adversarial to make the failure obvious; the real risk in production is the opposite of obvious, a financial aggregation that's subtly, silently off by a small relative amount that doesn't trigger any alarm because the number still looks plausible. The most common mistake in practice is assuming a wider accumulator type (switching float to double) fully solves the problem, when it only raises the bar at which the same class of error reappears; for a sum whose scale is genuinely large enough, or whose correctness is high-stakes enough (a financial ledger, in particular), compensated summation or an exact fixed-point representation is the more robust fix, not simply a wider floating-point type.
Design a secure over-the-air (OTA) update mechanism for constrained IoT devices. Requirements: authenticate images, protect against rollback, ensure integrity, minimize bandwidth, and recover from interrupted updates. Specify cryptographic primitives, image metadata, verification flow, and how delta updates might be applied safely.
Sample Answer
Clarify requirements & constraints
- Constrained MCU (KB–MB flash, limited RAM), intermittent power, limited bandwidth, need auth, anti-rollback, integrity, resume, delta support. Secure boot/root key in immutable ROM.
High-level design
- Dual-bank A/B layout with bootloader in ROM/immutable flash. Bootloader enforces verification and atomic switch.
- Root key: Ed25519 public key stored in ROM (or fused). Use signatures for authenticity; use HKDF + AES-GCM for optional encrypted payloads.
Cryptographic primitives
- Signature: Ed25519 (small, fast, safe against misuse).
- Integrity/MAC for streamed ops: SHA-256 for hashes; AES-128-GCM for authenticated encryption (if confidentiality needed).
- KDF: HKDF-SHA256 for deriving ephemeral keys for delta patches.
Image metadata
- image_length
- image_version (monotonic increment)
- rollback_counter (monotonic)
- base_hash (SHA-256 of base image if delta)
- image_hash (SHA-256 of full image or post-patch)
- signature (Ed25519 over metadata || image_hash)
- flags: delta/applied/compressed
- compression type, patch algorithm id
Verification & update flow
- Transfer image (or delta) to temporary staging region with progress checkpointing.
- Verify signature: compute image_hash (for delta, verify base_hash matches running image) then verify Ed25519(signature, metadata || image_hash) using ROM public key.
- Check rollback: require image_version > stored_monotonic_version (stored in secure monotonic flash or anti-rollback counter area). Only accept greater.
- Integrity: verify SHA-256 matches.
- Apply update:
- For full image: atomically write to inactive bank; verify write by re-hashing.
- For delta: verify base_hash equals active bank hash; apply patch to inactive bank while streaming and computing SHA-256; if patch fails, abort.
- Commit: update monotonic_version atomically (use small atomic write or hardware monotonic counter), set boot flag to boot new bank, trigger watchdog reset.
- Bootloader validates new bank at next boot; if validation fails or boot doesn't complete within watchdog timeout, auto-rollback to previous bank.
Rollback protection
- Monotonic counter stored in write-once / monotonic storage if available, or in redundant, wear-leveled flash with anti-tamper logic; require image_version > stored value before commit. Only increment after successful full verification to avoid fork.
Interrupted updates & recovery
- Chunked transfer with checkpointed offsets; keep both banks intact until new bank verified.
- If interruption, resume transfer using checkpoint; if patching interrupted, discard incomplete inactive bank and resume from last validated chunk.
- Watchdog + bootloader timeout ensures failed boots revert to known-good bank.
Delta updates safety
- Use content-addressed deltas: patch signed server-side producing patch_blob plus base_hash and resulting image_hash.
- Before applying, verify active image hash == base_hash. Reject if mismatch.
- Apply patch in streaming manner to inactive bank, computing hash on the fly. Use checksums per chunk to detect mid-patch corruption.
- Optionally use Merkle-tree or chunked hashes to allow partial verification and resume of patching, minimizing retransfer.
Bandwidth minimization
- Compress payload (zstd/DEFLATE), send binary delta (bsdiff or custom block-diff), use chunked transfers with HTTP range or CoAP block-wise transfers.
Practical considerations
- Keep bootloader minimal and well-audited.
- Test failure modes, power-loss during write, and ensure flash wear leveling.
- Log update attempts and failures to a persistent slot for diagnostics.
This design balances security (Ed25519, SHA-256, monotonic version), reliability (A/B + watchdog), and bandwidth (signed deltas + compression) suitable for constrained embedded devices.
Explain why C bitfields are generally discouraged for mapping hardware registers. Give two examples where compiler implementation choices (padding, bit order, signedness) cause incorrect behavior for MMIO. Then show a short example of a portable alternative using explicit masks and shifts for a 16-bit register with two 6-bit fields and one 4-bit field.
Sample Answer
Why bitfields are discouraged for MMIO
- Bitfield layout, packing, and ordering are implementation-defined in C, so using them to map hardware registers can produce incorrect accesses across compilers, ABIs, or optimization levels.
- MMIO requires precise atomic-sized reads/writes and exact bit positions; compiler choices can silently change behavior.
Two concrete problematic compiler choices
- Padding/packing: A compiler may insert padding between bitfields or align the whole struct to 32 bits. That changes offsets so the wrong register bits are read/written.
- Bit order & signedness: Some compilers assign the first declared bitfield to the low bits (LSB-first), others to high bits (MSB-first). Also, a narrow signed bitfield can perform sign extension on read/write, corrupting upper bits when accessed as unsigned MMIO.
Portable alternative (16-bit register: F1=6 bits, F2=6 bits, F3=4 bits)
- Use explicit masks and shifts; perform single 16-bit atomic accesses.
#include <stdint.h>
#define REG16_ADDR ((volatile uint16_t *)0x4000U)
#define F1_SHIFT 0
#define F1_MASK (0x3FU << F1_SHIFT) // 6 bits
#define F2_SHIFT 6
#define F2_MASK (0x3FU << F2_SHIFT) // 6 bits
#define F3_SHIFT 12
#define F3_MASK (0xFU << F3_SHIFT) // 4 bits
static inline uint16_t reg16_read(void) {
return *REG16_ADDR;
}
static inline void reg16_write(uint16_t v) {
*REG16_ADDR = v;
}
static inline uint16_t reg_get_f1(void) {
return (reg16_read() & F1_MASK) >> F1_SHIFT;
}
static inline void reg_set_f1(uint16_t val) {
uint16_t r = reg16_read();
r = (r & ~F1_MASK) | ((val << F1_SHIFT) & F1_MASK);
reg16_write(r);
}
/* Similar getters/setters for F2 and F3 */
This guarantees correct bit placement, avoids compiler packing/ordering surprises, and keeps accesses explicit and portable.
Want to create your own tailored preparation guide using our deep research?
Get Started for FreeInterview-Ready Courses
Visual-first, interactive, structured learning paths
Browse Embedded Developer jobs
AI-enriched listings across hundreds of company career pages
Explore Jobs