Common Pitfalls
Avoiding common C++ mistakes
Interview Relevant: Code review knowledge
Common Pitfalls
Even experienced developers can fall into these C++ traps.
Watch Out For
- Dangling References: Returning reference to local variable.
- Iterator Invalidation: Modifying a container while iterating.
- Slicing: Assigning derived object to base instance (loses data).
- Undefined Behavior (UB): Accessing out of bounds, uninitialized variables.
Code Examples
Common C++ mistakes and how to avoid them.
cpp
1// 1. Dangling reference
2const string& getDangling() {
3 string local = "hello";
4 return local; // Dangling reference!
5}
6
7// 2. Use after move
8string s = "hello";
9string s2 = move(s);
10cout << s; // Undefined! s is in valid but unspecified state
11
12// 3. Iterator invalidation
13vector<int> v = {1, 2, 3};
14for (auto it = v.begin(); it != v.end(); ++it) {
15 if (*it == 2) v.push_back(4); // Invalidates iterators!
16}
17
18// 4. Slicing
19class Base { virtual void foo() {} };
20class Derived : public Base { int x; };
21Base b = Derived(); // Sliced! x is lost
22
23// 5. Integer overflow
24int x = INT_MAX;
25x++; // Undefined behavior!
26
27// 6. Forgetting virtual destructor
28class Base {
29public:
30 ~Base() {} // Not virtual!
31};
32Base* b = new Derived();
33delete b; // Derived destructor not called!
34
35// 7. Uninitialized variables
36int x; // Garbage value!
37cout << x;
38
39// 8. Off-by-one errors
40for (int i = 0; i <= size; i++) { } // Often wrong!
41
42// 9. Double delete
43int* p = new int;
44delete p;
45delete p; // Crash!