Common Pitfalls
Certain mistakes show up again and again in C++ code, from beginner scripts to production codebases. Most of them compile without complaint and only misbehave at runtime — sometimes only occasionally, which makes them especially frustrating to track down. This page is a quick reference for what to watch for.
Pitfall | Why it bites |
|---|---|
Uninitialized variables | A local variable with no initializer holds whatever garbage was already in that memory — not zero. Reading it is undefined behavior, and it can even appear to "work" for a while before failing. |
Dangling pointers/references | A pointer or reference to an object that has already been destroyed (e.g. a local variable after the function returned, or memory already |
Off-by-one errors | Looping with |
Mixing signed and unsigned comparisons | Comparing a signed |
Integer division truncation |
|
Shallow copy of resource-owning classes | Without a proper copy constructor, the compiler-generated one copies a raw pointer member as-is. Both copies then point at the same heap memory, and destroying one leaves the other holding a dangling pointer (and a double-free waiting to happen). |
Missing virtual destructor in a polymorphic base |
|
Memory leaks from mismatched new/delete | Every |
Using |
|
Array-to-pointer decay in function parameters | Passing a C array to a function that takes |
a-few-of-these-in-action.cpp
#include <cstddef>
#include <iostream>
void printSize(int arr[]) {
// arr has decayed to a pointer here — this is sizeof(int*), not the array size!
std::cout << "sizeof inside function: " << sizeof(arr) << "\n";
}
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
std::cout << "sizeof in main: " << sizeof(numbers) << "\n"; // 20 bytes
printSize(numbers); // 8 bytes (a pointer)
int x;
if (x = 5) { // bug: assignment, not comparison — also uses uninitialized x
std::cout << "This always runs, x is now 5\n";
}
std::size_t count = 3;
int i = -1;
if (i < count) { // i converts to a huge unsigned number — condition is false!
std::cout << "unreachable on most compilers\n";
}
return 0;
}