Top 10 C scenario questions
Try each one yourself first, then open the model answer.
1. A program crashes when copying user input into a fixed buffer. What is wrong and how do you fix it?
Show answerHide answer
The input overflows the buffer. Check lengths, use bounded functions such as snprintf, and ensure there is room for the terminating null.
2. sizeof on an array parameter returns the size of a pointer. Why?
Show answerHide answer
Array parameters are adjusted to pointers. Pass the element count as a separate argument.
3. You call free on a pointer twice. How can you reduce such bugs?
Show answerHide answer
A double free is undefined behaviour. Define clear ownership, set pointers to NULL after freeing where helpful, and test with Valgrind or AddressSanitizer.
4. realloc fails and your program leaks the original block. What did you do wrong?
Show answerHide answer
Assigning the result directly to the original pointer loses it when NULL is returned. Store the result in a temporary pointer and assign only on success.
5. A variable changed by an interrupt handler is never seen by the main loop. What do you do?
Show answerHide answer
Declare it volatile so the compiler reads it each time, and consider atomic types or disabling interrupts for multi-byte or read-modify-write access.
6. Two strings with the same text are not equal using ==. Why?
Show answerHide answer
== compares addresses. Use strcmp or strncmp and check for zero.
7. A struct written to a file on one machine is read incorrectly on another. Why?
Show answerHide answer
Padding, type sizes and byte order can differ. Serialise each field explicitly with fixed-width types and a defined endianness.
8. A macro SQUARE(x) gives the wrong answer for SQUARE(a+1). How do you fix it?
Show answerHide answer
Macros substitute text. Parenthesise the parameter and the whole expression, or better use a static inline function, which also avoids evaluating arguments twice.
9. A function returns a pointer to a local array. What happens?
Show answerHide answer
The storage no longer exists after return. Have the caller supply a buffer, or allocate memory and document who frees it.
10. Signed integer overflow makes a safety check disappear after optimisation. Why?
Show answerHide answer
Signed overflow is undefined, so the compiler may assume it never happens. Check the limits before the operation rather than after.
