Challenge - 5 Problems
Error Handling Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of perror after a failed fopen?
Consider the following C code snippet. What will be printed to the standard error when fopen fails to open a non-existent file?
C
#include <stdio.h> #include <errno.h> int main() { FILE *fp = fopen("nonexistent.txt", "r"); if (!fp) { perror("Error opening file"); } return 0; }
Attempts:
2 left
💡 Hint
The file does not exist, so fopen sets errno to ENOENT.
✗ Incorrect
When fopen fails because the file does not exist, errno is set to ENOENT. perror prints the string passed to it, followed by a colon, a space, and the error message corresponding to errno.
❓ Predict Output
intermediate2:00remaining
What does strerror return for errno 13?
What string does strerror return when errno is set to 13?
C
#include <stdio.h> #include <string.h> #include <errno.h> int main() { errno = 13; printf("%s\n", strerror(errno)); return 0; }
Attempts:
2 left
💡 Hint
Errno 13 corresponds to a permission problem.
✗ Incorrect
Errno 13 is defined as EACCES, which means 'Permission denied'. strerror returns the string describing the error code.
🔧 Debug
advanced2:00remaining
Why does this perror call print an empty message?
Examine the code below. Why does perror print only a newline without any message?
C
#include <stdio.h> #include <errno.h> int main() { errno = 0; perror(""); return 0; }
Attempts:
2 left
💡 Hint
Check what errno value means zero and how perror behaves with empty string.
✗ Incorrect
When errno is zero, it means no error. perror prints the string passed to it, then ': ', then the error message. If the string is empty and errno is zero, it prints only a newline.
📝 Syntax
advanced2:00remaining
Which option correctly uses strerror to print an error message?
Select the code snippet that correctly prints the error message for the current errno using strerror.
Attempts:
2 left
💡 Hint
strerror requires an integer error code as argument.
✗ Incorrect
strerror takes an integer error code (like errno) and returns a string describing the error. Option A correctly passes errno to strerror.
🚀 Application
expert3:00remaining
How to safely print a custom error message with strerror in a multithreaded program?
In a multithreaded C program, which approach is safest to print a custom error message with the error string corresponding to errno?
Attempts:
2 left
💡 Hint
strerror is not thread-safe, but strerror_r is designed for thread safety.
✗ Incorrect
strerror is not thread-safe because it may return a pointer to a static buffer. strerror_r is a thread-safe alternative that writes the error message into a user-provided buffer.