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:
error: expected ',' or ';' before 'printf'
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 a string
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:
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:
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:
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.