Common Pitfalls
Most bugs beginners (and plenty of experienced programmers) hit in C fall into a fairly short, well-known list. Recognizing the pattern instantly is often enough to avoid it entirely — this page is a curated reference of the most frequent ones.
Pitfall | Example / explanation |
|---|---|
Using |
|
Forgetting |
|
Buffer overflows from unbounded string functions | Using |
Off-by-one errors |
|
Uninitialized variables | Reading a local variable before assigning it gives an indeterminate value -- not guaranteed to be zero, and technically undefined behavior |
Dangling / wild pointers | Using a pointer after |
Memory leaks | Losing the only pointer to a |
Mismatched printf format specifiers | Using |
Integer overflow | Signed overflow (e.g. |
Comparing floats with | Floating-point rounding means two mathematically-equal values can differ by a tiny epsilon -- compare with a tolerance instead, e.g. |
#include <stdio.h>
int main(void) {
int x = 5;
// Pitfall: assignment instead of comparison -- this is ALWAYS true.
if (x = 10) {
printf("This always runs, and x is now 10!\n");
}
// Pitfall: comparing floats directly.
double a = 0.1 + 0.2;
double b = 0.3;
if (a == b) {
printf("Equal\n");
} else {
printf("Not equal -- floating point rounding!\n"); // this prints
}
return 0;
}