Which of the following best explains why error handling is important in C programs?
Think about what happens if something goes wrong while the program runs.
Error handling helps programs detect problems like missing files or invalid input and respond properly instead of crashing.
What will this C program print if the file data.txt does not exist?
#include <stdio.h> int main() { FILE *f = fopen("data.txt", "r"); if (f == NULL) { printf("Error opening file\n"); } else { printf("File opened successfully\n"); fclose(f); } return 0; }
What does fopen return if the file is missing?
If the file does not exist, fopen returns NULL, so the program prints the error message.
What happens when this C program tries to read from a file that does not exist?
#include <stdio.h> int main() { FILE *f = fopen("nofile.txt", "r"); char buffer[10]; fread(buffer, sizeof(char), 10, f); printf("Read data: %s\n", buffer); fclose(f); return 0; }
What happens if you use a file pointer that is NULL?
Since fopen returns NULL when the file is missing, using it in fread causes undefined behavior, often a crash.
Why is it important to check return values of functions like malloc or fopen in C?
Think about what happens if memory allocation or file opening fails.
Functions like malloc and fopen return NULL on failure, so checking their return values helps avoid crashes or undefined behavior.
What is the main error handling mistake in this C code snippet?
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = malloc(sizeof(int) * 5); *ptr = 10; printf("Value: %d\n", *ptr); free(ptr); return 0; }
What happens if malloc fails?
If malloc fails, it returns NULL. Using the pointer without checking causes undefined behavior or crashes.