Unlike modern languages (like Python or Java), C does not have built-in "exceptions" (like try/catch blocks). Instead, you must manually check for errors, validate inputs, and debug memory issues. Mastering these concepts separates average programmers from elite C developers.
A NULL pointer is a pointer that points to nothing (address 0). It is heavily used in C to indicate failure—for example, when a file cannot be opened or memory allocation (malloc) fails.
Rule of Thumb: Never dereference a pointer without checking if it is NULL first!
#include <stdio.h> #include <stdlib.h>int main() { int *ptr = malloc(sizeof(int)); // Validate that memory was successfully allocated if (ptr == NULL) { printf("Memory allocation failed!\n"); return 1; // Exit with error code } *ptr = 100; printf("Value: %d\n", *ptr); free(ptr); return 0; }
When standard C library functions fail, they usually return -1 or NULL and set a global variable called errno. You can use the perror() or strerror() functions to print human-readable error messages based on errno.
#include <stdio.h> #include <errno.h>int main() { // Attempting to open a non-existent file for reading FILE *file = fopen("does_not_exist.txt", "r"); if (file == NULL) { // perror automatically reads 'errno' and prints the error description perror("Failed to open file"); } return 0; }
Never trust user input. If you expect a number but the user types text, scanf() will fail and leave the text in the input buffer, causing infinite loops or crashes in your program.
You should always check the return value of scanf(), which returns the number of successfully read items. Furthermore, you must flush the input buffer on failure.
#include <stdio.h>int main() { int age; printf("Enter your age: "); // scanf returns 1 if it successfully read one integer while (scanf("%d", &age) != 1) { printf("Invalid input. Please enter a valid number: "); // Clear the invalid characters from the buffer while (getchar() != '\n'); } printf("You are %d years old.\n", age); return 0; }
When your C code compiles but behaves unexpectedly, you must debug it.
printf() statements in your code to check variable states.assert(): The <assert.h> library provides the assert() macro. It aborts the program if a given condition is false, making it incredible for testing assumptions during development.#include <stdio.h> #include <assert.h>float divide(float a, float b) { // Program will instantly crash and point to this line if b is 0. assert(b != 0.0 && "Error: Division by zero!"); return a / b; }
int main() { printf("Result: %.2f\n", divide(10.0, 2.0)); // printf("Result: %.2f\n", divide(10.0, 0.0)); // Uncommenting this triggers assert return 0; }
What global variable is automatically set by C library functions when they encounter an error?