15. Error Handling & DebuggingAdvanced11 min read
Error Handling, GDB Debugging & Memory Safety in C
Diagnose crashes, catch system errors using errno & perror, debug with GDB, and detect memory leaks using Valgrind.
Key Takeaways & Core Concepts
errnois a global thread-local integer set by system calls and library functions upon failure.perror("prefix")prints a human-readable description of the currenterrnoto stderr.strerror(errno)returns the error message string defined in<string.h>.- GDB commands:
b main(breakpoint),r(run),n(next),s(step into),p var(print),bt(backtrace). - Valgrind detects memory leaks, invalid heap reads/writes, and double frees.
Standard Error Handling with errno & perror()
When a C standard library function (like fopen, malloc, or math functions) fails, it updates the integer errno defined in <errno.h>.
Catching System Errors with errno and perror()
1#include <stdio.h>
2#include <errno.h>
3#include <string.h>
4
5int main(void) {
6 FILE *fp = fopen("non_existent_file_xyz.txt", "r");
7 if (fp == NULL) {
8 printf("Current errno value: %d\n", errno);
9 perror("Error via perror");
10 printf("Error via strerror: %s\n", strerror(errno));
11 return 1;
12 }
13 fclose(fp);
14 return 0;
15}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
15 lines
Note: errno 2 corresponds to ENOENT ('No such file or directory').
Practice & AssessmentC Programming Complete Course
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 1 correct(0 attempted)
1
Which header file must be included to access the errno variable?
BeginnerPrevious Lesson
14. Data Structures & Algorithms
Searching & Sorting Algorithms in C
12 min read
Congratulations!
You completed all course lessons in this track!