Embedded C Interview Questions for Automotive Engineers

Strong embedded C interviews test whether a candidate can connect language rules to hardware behavior, concurrency, timing and fault handling. An effective answer explains not only what a feature does, but also the failure mode it prevents, the constraints of the target microcontroller and how the implementation would be verified.

The questions below focus on practical ECU engineering. They cover C language fundamentals, memory, pointers, hardware access, interrupts, real-time behavior, diagnostics and coding exercises.

1. C language and memory

1. What does volatile mean?

volatile tells the compiler that accesses through the qualified lvalue are observable and must follow the implementation's volatile-access rules. The compiler must not treat the object as an ordinary value that cannot change unexpectedly.

Common embedded uses include memory-mapped peripheral registers, status flags updated by hardware and some objects shared with an interrupt handler. volatile does not make an access atomic, provide mutual exclusion, or create general inter-thread synchronization. A volatile increment such as counter++ is still a read-modify-write operation.

Interview follow-up: How would you protect a counter shared between an ISR and a task? A suitable answer discusses target-supported atomic operations, a bounded interrupt-safe critical section, or a data-exchange design with clearly defined ownership. The correct choice depends on access width, compiler support and ISR requirements.

2. What is the difference between const and volatile?

const prevents modification through the qualified lvalue. volatile affects how accesses are treated by the compiler. They can be combined:

volatile const uint32_t *status_reg;

This represents a pointer to a volatile object that software must not modify through this pointer. It is a useful conceptual model for a hardware status register that can change independently of the program.

The qualifiers apply at specific levels of indirection:

const uint8_t *p;             /* Pointer to const uint8_t */
uint8_t * const p2 = 0;       /* Const pointer to uint8_t */
const uint8_t * const p3 = 0; /* Const pointer to const uint8_t */

Be prepared to explain whether the pointer, the pointed-to object, or both are qualified.

3. What is the difference between stack and heap memory?

The stack typically stores function call frames and automatic objects whose lifetimes are associated with block execution. The heap supports dynamic allocation, where storage is requested and released at runtime.

Embedded projects often restrict or prohibit runtime heap allocation, especially in safety-related or highly deterministic software, because it can introduce allocation failure, fragmentation, variable execution time, ownership errors and more difficult worst-case memory analysis. Fixed-size pools or statically allocated buffers can be more predictable when capacity and ownership rules are carefully designed.

4. What is a dangling pointer?

A dangling pointer refers to an object whose lifetime has ended or to storage that is no longer valid. A common error is returning the address of a local automatic variable:

int *get_value_pointer(void)
{
    int local_value = 10;
    return &local_value; /* Invalid after this function returns */
}

Other causes include using a pointer after freeing its allocation, retaining a pointer into a buffer that has been reused, or accessing an object outside its lifetime. Dereferencing a dangling pointer has undefined behavior.

5. Why does structure padding matter?

The compiler may insert padding between structure members, or at the end of a structure, to satisfy alignment requirements. Therefore, sizeof(struct) may be larger than the sum of the member sizes.

#include <stdint.h>

struct Example
{
    uint8_t  first;
    uint32_t second;
    uint16_t third;
};

The exact layout depends on the target ABI, compiler and alignment rules. Do not assume a C structure's in-memory layout is a CAN, Ethernet, UDS or other wire format. Serialize and deserialize fields explicitly with defined widths, byte order and bounds checks.

6. What is undefined behavior in C?

Undefined behavior means the C standard imposes no requirements on the result of that execution. Examples include signed integer overflow, out-of-bounds array access, dereferencing an invalid or null pointer, certain violations of aliasing rules and using an uninitialized automatic object.

A program may appear to work in a debug build and fail after compiler optimization. Prevent undefined behavior, enable compiler diagnostics and static analysis, and test boundary conditions.

7. What is the difference between static at file scope and block scope?

At file scope, static gives an object or function internal linkage: it is visible only within that translation unit. At block scope, static gives a local object static storage duration. It retains its value between function calls, even though its identifier is visible only within the block.

static uint32_t module_counter; /* File scope: internal linkage */

void update_counter(void)
{
    static uint16_t call_count; /* Retains value between calls */
    call_count++;
}

Static storage duration does not make an object automatically thread-safe. If multiple execution contexts access it, concurrency rules still apply.

8. What is the difference between a pointer and an array?

An array is an object containing a fixed sequence of elements. In many expressions, an array expression is converted to a pointer to its first element, but an array is not itself a pointer.

uint8_t data[8];
uint8_t *ptr = data;

sizeof(data) gives the size of the complete array in this scope, while sizeof(ptr) gives the size of the pointer. When an array is passed as a function parameter, the parameter is adjusted to a pointer type, so the function does not receive the array's size automatically. Pass the length separately.

2. Hardware and concurrency

9. Why use volatile for a hardware register?

A peripheral register can change because of hardware activity independently of the current instruction flow. A volatile-qualified access tells the compiler that the access is observable and must be performed according to the implementation's volatile rules.

Use the MCU vendor's register definitions or a verified hardware abstraction layer. Confirm the register address and access width, read/write behavior, ordering requirements, write-one-to-clear or read-to-clear semantics, and whether an access has side effects. volatile does not replace memory barriers or peripheral synchronization mechanisms where the architecture requires them.

10. Can volatile make an ISR-shared counter safe?

No. Consider:

volatile uint32_t tick_count;

void timer_isr(void)
{
    tick_count++;
}

The increment is a read-modify-write sequence. If foreground code also modifies the counter, or if the target cannot perform the access atomically, updates can be lost or values can be observed inconsistently.

Possible approaches include a target-supported atomic operation suitable for interrupt context, a short critical section, a single-writer design, or a queue/event mechanism when individual events must be preserved. Do not assume every C atomic operation is lock-free or safe inside an ISR; check the compiler, architecture and generated implementation.

11. What is the difference between polling, interrupts and DMA?

Polling repeatedly checks a peripheral status or data condition. It can be simple and deterministic in a tightly controlled loop, but consumes CPU time and may add detection latency.

Interrupts notify the CPU when an event occurs. They can reduce unnecessary polling, but introduce priority, concurrency, latency and shared-data concerns.

Direct memory access (DMA) transfers data between a peripheral and memory with less CPU involvement. It is useful for higher-volume or continuous transfers, but requires careful buffer ownership, completion handling and, on systems with caches, cache-coherency management.

These mechanisms can be combined. DMA may transfer a communication buffer while an interrupt reports transfer completion.

12. What makes a good interrupt service routine?

A good ISR is short, bounded and non-blocking. It normally identifies and acknowledges the source, captures the minimum data needed immediately, updates bounded state or publishes an event, notifies a task using an ISR-safe mechanism if applicable, and returns promptly.

Avoid blocking calls, dynamic allocation, long loops, slow logging and task-context APIs that are not documented as ISR-safe. Measure execution time and consider nesting and priority effects.

13. What is a race condition?

A race condition occurs when a result depends on the timing or interleaving of concurrent operations. In an ECU, it can occur when an ISR and a task access shared data without a defined ownership or synchronization protocol.

Examples include a task reading a multi-byte counter while an ISR updates it, a producer overwriting a buffer before the consumer finishes reading it, or a consumer clearing a flag just as the producer sets it. The solution is not simply to add volatile: define ownership, atomicity, ordering and behavior when events arrive faster than they can be consumed.

14. What is a critical section?

A critical section is a bounded region in which a specific operation is protected from conflicting concurrent access. On a single-core MCU, one common mechanism is to mask relevant interrupts temporarily.

Critical sections should be as short as possible. Excessive interrupt masking increases worst-case latency and may cause missed deadlines. The implementation must preserve the previous interrupt-mask state correctly; blindly enabling interrupts at the end can break a caller that entered with interrupts already disabled. In an RTOS or multicore environment, use the synchronization primitive appropriate to the execution context and platform.

3. Timing and real-time behavior

15. What is the difference between latency and jitter?

Latency is the delay from an event to a response. Jitter is variation in timing, such as variation in the interval between periodic task executions or in event-to-response delay. A control function may tolerate a certain fixed latency but be sensitive to excessive jitter. Both must be evaluated against system requirements.

16. How do you calculate a timer period?

Determine the actual timer input clock, prescaler division behavior, counting mode, reload/auto-reload semantics, whether the count includes zero and the terminal count, and any clock multipliers or bus-clock rules.

For a common edge-aligned up-counter:

T=P×NftimerT = \frac{P \times N}{f_{\text{timer}}}

where PP is the prescaler division factor, NN is the number of timer ticks per period and ftimerf_{\text{timer}} is the timer input clock. Calculate the expected period, then measure it on target hardware. Do not assume register values are identical to division factors or tick counts.

17. What is worst-case execution time (WCET)?

WCET is a defensible upper bound on the execution time of a software unit under a defined set of hardware, input and system conditions. Average execution time is not enough to prove deadline compliance.

Analysis may need to account for longest execution paths and loop bounds, interrupt pre-emption, cache misses or flash wait states where applicable, bus and memory contention, compiler settings, and hardware/software configuration. Measurement is useful evidence, but a finite set of measurements alone does not necessarily establish a true worst-case bound.

18. What happens when a counter overflows?

An unsigned integer wraps modulo one more than its maximum representable value. Signed integer overflow is undefined behavior in C.

For elapsed-time measurement, unsigned modular subtraction can be useful:

uint32_t elapsed = (uint32_t)(now - start);

This is valid when the interval is known to be shorter than one complete counter wrap and the counter values are read consistently. If the interval may span multiple wraps, extend the time base or use a wider time source with a synchronized read method.

19. What is the difference between a periodic task and an event-triggered task?

A periodic task is released at a configured interval, often using a timer or RTOS scheduler. An event-triggered task is released when a specific event occurs, such as message reception or conversion completion.

Periodic execution is useful for fixed-rate control and supervision. Event-triggered execution can avoid unnecessary work when events are sparse. Both need defined priorities, execution budgets, response-time requirements and overload behavior.

4. ECU software design and diagnostics

20. Why use fixed-width integer types?

Types such as uint8_t, uint16_t, uint32_t and their signed equivalents make data widths explicit when those optional exact-width types are provided by the implementation.

They are useful for peripheral registers, protocol fields, calibration and measurement values, bit masks and status words. Still consider integer promotions, alignment, endianness and arithmetic range. A fixed-width type does not automatically make an operation safe from overflow.

21. Why should protocol serialization avoid raw C structures?

Structure padding, alignment, endianness and compiler ABI can differ. A raw structure copy can therefore produce a different byte layout from the protocol definition.

Encode and decode each field explicitly. Validate input length before accessing bytes, use defined byte order and check numeric ranges before conversion. This is important for CAN signals, diagnostic messages and application protocols carried over automotive networks.

22. What is a watchdog?

A watchdog is a hardware or software mechanism that detects failure to make expected progress. If it is not serviced within its configured window, it may trigger a reset or another defined reaction.

A robust design should not service the watchdog unconditionally from a periodic timer ISR. That could keep the watchdog alive even if a critical task has stopped functioning. Instead, service it only after relevant health checks demonstrate that required tasks and functions have made progress. The strategy must match the safety concept and watchdog architecture.

23. How would you debug an intermittent ECU reset?

Use a structured approach:

  1. Capture reset-cause flags as early as possible during startup, before software clears or overwrites them.
  2. Check watchdog, brownout, power-on reset and external reset indications.
  3. Inspect fault/status registers and retained diagnostic information.
  4. Monitor supply voltage, ground, reset pin and relevant clock signals.
  5. Check stack usage, memory corruption and exception/fault handlers.
  6. Correlate reset timestamps with communication load, actuator activity and software events.
  7. Reproduce under controlled voltage, temperature, load and timing conditions where appropriate.

Avoid assuming every unexplained reset is a watchdog reset. Preserve evidence before clearing flags.

24. What is defensive handling of an invalid sensor value?

Validate more than the numeric range. Depending on the signal and system requirements, checks may include range and electrical plausibility, freshness and timeout, rate of change, cross-checks against redundant or related signals, and sensor status or communication integrity.

Then apply the defined degraded or safe response and report diagnostics according to system requirements. Do not silently clamp every invalid value unless that behavior is justified by the control strategy and safety concept.

25. What is the purpose of a diagnostic trouble code (DTC)?

A DTC records a detected fault according to the diagnostic strategy and applicable diagnostic specification. Detection, qualification, confirmation, aging and clearing are separate behaviors that depend on the diagnostic design.

Distinguish the fault-monitoring logic from the diagnostic communication service used to read or clear DTC information. A DTC is not simply an arbitrary error number printed by application code.

5. Short coding exercises

Exercise A: Check a byte range safely

Question: Given a buffer size, an offset and a requested length, determine whether the requested range is fully inside the buffer without allowing integer overflow.

#include <stdbool.h>
#include <stddef.h>

bool range_is_valid(size_t offset, size_t length, size_t total)
{
    /* Subtraction form avoids overflow in offset + length. */
    return (offset <= total) && (length <= (total - offset));
}

The first condition ensures the subtraction is valid. The second ensures the requested length fits in the remaining range.

Exercise B: Decode a big-endian 16-bit value

Question: Read two bytes from a buffer and decode them as a big-endian unsigned 16-bit value.

#include <stdint.h>
#include <stdbool.h>

bool read_u16_be(const uint8_t *data,
                 uint32_t length,
                 uint32_t offset,
                 uint16_t *value)
{
    if ((data == 0) || (value == 0) ||
        (offset > length) || ((length - offset) < 2U))
    {
        return false;
    }

    *value = (uint16_t)(((uint16_t)data[offset] << 8) |
                       (uint16_t)data[offset + 1U]);

    return true;
}

Discuss the pointer contract, null checks, length validation, integer promotion and byte order. In a production API, also define whether value may alias the input buffer and follow project-specific coding rules.

Exercise C: Set and clear a bit

Question: Set bit 3 and then clear bit 3 in an unsigned status word.

#include <stdint.h>

uint32_t status = 0U;

status |= (uint32_t)(1UL << 3U);  /* Set bit 3 */
status &= (uint32_t)~(1UL << 3U); /* Clear bit 3 */

For portable code, ensure the left operand has an appropriate unsigned type and that the shift count is less than the width of the promoted operand. For hardware registers, confirm whether read-modify-write is permitted; some registers require dedicated set/clear aliases or special write semantics.

Exercise D: Explain a safe ISR-to-task notification

Question: A timer ISR increments an event count, and a task reads it. What can go wrong?

A candidate should explain that a read-modify-write operation may not be atomic, that access width matters, and that volatile alone is insufficient. A correct solution might use a target-supported atomic counter, a short critical section to take a consistent snapshot, or an ISR-safe queue if each event must be preserved.

6. Scenario-based interview questions

Scenario 1: A 1 ms task occasionally runs late. How would you investigate?

Define the release time, start time, completion time and deadline. Measure release jitter and execution time separately. Inspect higher-priority tasks and ISRs, critical sections, interrupt masking, bus contention and blocking synchronization. Reproduce under representative load and correlate traces with communication and peripheral activity.

Scenario 2: A CAN message parser sometimes reports an invalid signal value.

Check received frame length and identifier before accessing payload bytes. Confirm byte order, bit positions, signedness, scaling and offset against the interface definition. Validate signal range and message freshness, and inspect whether the buffer can be modified while parsing. Add boundary tests and retain the raw frame and timestamp for diagnosis.

Scenario 3: The watchdog resets the ECU even though its timer ISR is running.

A running timer ISR does not prove that the application is healthy. Check whether critical tasks are making progress, whether a deadlocked task is preventing a health condition, and whether the watchdog is serviced from an inappropriate context. Review reset-cause evidence and the watchdog servicing architecture.

Scenario 4: A periodic timer has the correct average frequency but the output timing varies.

Investigate whether the output is changed in software after ISR entry or directly by a hardware compare/PWM channel. Software scheduling can add variable latency. Consider hardware output compare, timer synchronization, interrupt load and the measurement point. Compare event timing and output timing separately.

7. How to structure a strong interview answer

For a practical embedded question, explain:

  1. The rule: State the relevant C language, MCU or real-time behavior.
  2. The risk: Describe what can fail if the rule is misunderstood.
  3. The design: Explain the technique you would use and its assumptions.
  4. The verification: Describe how you would test or measure it on target hardware.

For example, do not answer an ISR-sharing question with only “declare it volatile.” Explain access width, atomicity, ownership, critical-section duration, event-loss behavior and how stress testing would expose defects.

If you do not know a device-specific detail, say which reference-manual section or compiler documentation you would check. That is better engineering judgment than inventing a universal register behavior.

8. Self-assessment checklist

  • Explain volatile, const, static and storage duration.
  • Distinguish pointers from arrays and explain pointer lifetime.
  • Identify undefined behavior and bounds errors.
  • Explain stack, heap, alignment and structure padding.
  • Design safe ISR-to-task data exchange.
  • Explain polling, interrupts and DMA trade-offs.
  • Calculate timer periods and reason about latency and jitter.
  • Explain unsigned wraparound and safe elapsed-time measurement.
  • Decode protocol fields without relying on compiler structure layout.
  • Explain watchdog servicing and reset diagnosis.
  • Validate sensor data and define fault responses.
  • Describe how to verify timing and functional behavior on target hardware.

Use these questions to assess fundamentals and practice explaining trade-offs. Exact coding rules, safety processes and hardware behavior depend on the employer, compiler, MCU and project baseline.

Related articles