C Errors
Errors
Even experienced C developers make mistakes. The key is learning how to spot and fix them!
These pages cover common errors and helpful debugging tips to help you understand what's going wrong and how to fix it.
Common Compile-Time Errors
Compile-time errors are mistakes that prevent your program from compiling.
1) Missing semicolon:
Example
#include <stdio.h>
int main() {
int x = 5
printf("%d", x);
return 0;
}
Result:
prog.c: In function 'main':
prog.c:5:3: error: expected ',' or ';' before 'printf'
5 | printf("%d", x);
| ^~~~~~
Tip: The error message also tells you where the error is: prog.c:5:3 means line 5, column 3, and the ^ marks the spot. Notice that the semicolon is missing on line 4, but the error is reported on line 5, where the compiler first noticed that something was missing. If you cannot find the error on the line the compiler shows, look at the line before it.
2) Using undeclared variables:
Example
#include <stdio.h>
int main() {
printf("%d", myVar);
return 0;
}
Result:
error: 'myVar' undeclared
3) Mismatched types (e.g. assigning text to an int):
Example
#include <stdio.h>
int main() {
int x = "Hello";
return 0;
}
Result:
error: initialization makes integer from pointer without a cast
Common Runtime Errors
Runtime errors occur when the program compiles but crashes or behaves unexpectedly.
1) Dividing by zero:
Dividing an integer by zero usually makes the program crash:
Example
#include <stdio.h>
int main() {
int x = 10;
int y = 0;
int result = x / y;
printf("%d\n", result); // not possible
return 0;
}
2) Accessing out-of-bounds array elements:
C does not check if the index exists, so the example below may print a random number, or make the program crash:
Example
#include <stdio.h>
int main() {
int numbers[3] = {1, 2, 3};
printf("%d\n", numbers[8]); // element does not exist
return 0;
}
3) Using freed memory:
The example below may print 10, a random number, or crash. This is called undefined behavior: C does not say what will happen, so you cannot trust the result.
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr = malloc(sizeof(int));
*ptr = 10;
free(ptr);
printf("%d\n", *ptr); // Undefined behavior - accessing memory that was freed
return 0;
}
Good Habits to Avoid Errors
- Always initialize your variables
- Use meaningful variable names
- Keep your code clean and use indentation to stay organized
- Keep functions short and focused
- Check if loops or conditions are running as expected
- Read error messages carefully - they often tell you exactly where the problem is
In the next chapter, you will learn how to debug your code - how to find and fix bugs/errors in your C program.