Interview Questions
Error Handling · Study material
Error Handling in C – Interview Questions
1. How are errors handled in C without exceptions?
Through return values (NULL, EOF, −1, error codes), errno for library functions, and program termination with exit or abort. setjmp/longjmp can jump out of nested calls.
2. What is errno?
A modifiable int lvalue (thread-local in modern libraries) declared in <errno.h>, set to a positive error number by failing library functions. It is never set to 0 by a library function.
3. Difference between perror and strerror?
perror(s) prints "s: message" to stderr; strerror(n) returns the message text for error number n.
4. What do EXIT_SUCCESS and EXIT_FAILURE mean?
Portable exit statuses from <stdlib.h>. EXIT_SUCCESS (like 0) means success; EXIT_FAILURE means failure.
5. What is the difference between exit() and abort()?
exit performs normal termination: atexit handlers, flushing and closing streams. abort raises SIGABRT and ends abnormally without them.
6. What happens to assert when NDEBUG is defined?
Each assert expands to nothing, so its expression is not even evaluated.
7. When would you use static_assert?
To check assumptions the compiler can evaluate: type sizes, struct layout, array lengths matching enum counts.
8. How does setjmp/longjmp work?
setjmp saves the execution context and returns 0; longjmp restores it, making setjmp return again with a non-zero value. Locals modified after setjmp must be volatile to have reliable values.
9. Why is atoi considered unsafe?
It has no way to report invalid input or overflow – out-of-range values are undefined behaviour. strtol reports both.
10. Is the goto statement acceptable for error handling?
Yes – forward jumps to a cleanup label are a widely accepted C idiom for releasing resources on every error path.
11. How do you detect integer overflow?
Check before the operation (e.g. a > INT_MAX − b) or use C23 ckd_add/ckd_sub/ckd_mul (or compiler builtins such as __builtin_add_overflow).
12. What may a signal handler safely do?
In portable C, assign to a volatile sig_atomic_t variable, call signal for the same signal, _Exit, abort or quick_exit.