There is a short list of bugs that show up again and again in the C++ code reviews, and they are worth learning by heart. Nearly all of them are about the lifetime of a piece of memory or about the boundary between the two kinds of number.
The previous lesson in this module covered "How Do CMake and Folder Structure Scale a Project?", and the next lesson in this module is about "What Goes Into a Complete Inventory Management CLI?".
The dangling reference
It usually arrives through a function that returns a reference to a local.
const std::string& bad_label() {
std::string label = "perishable";
return label; // the local dies when the function returns
}
int main() {
const std::string& label = bad_label();
std::cout << "label: " << label << '\n';
return 0;
}And the fix is to return by value.
#include <iostream>
#include <string>
std::string good_label() {
std::string label = "perishable";
return label; // the value is copied out, nothing dangles
}
int main() {
std::string label = good_label();
std::cout << "label: " << label << '\n';
return 0;
}The output is now defined.
label: perishableIterator invalidation
The code compiles and then it misbehaves.
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> items = {"a", "b"};
std::vector<std::string>::iterator it = items.begin();
items.push_back("c"); // may reallocate
std::cout << "first: " << *it << '\n';
return 0;
}And the fix is either to reserve the space first, to use an index instead of an iterator, or to recompute the iterator after the change.
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> items = {"a", "b"};
items.reserve(10); // no reallocation will happen now
std::vector<std::string>::iterator it = items.begin();
items.push_back("c");
std::cout << "first: " << *it << '\n';
return 0;
}The output is now reliable.
first: aSigned integer overflow
The signed overflow is undefined behaviour, and it usually shows up as a negative quantity where a positive one was expected.
#include <iostream>
int main() {
int total = 2000000000;
int doubled = total * 2; // overflow: undefined behaviour
std::cout << "doubled: " << doubled << '\n';
return 0;
}And the fix is to use a type that can hold the result.
#include <iostream>
int main() {
int total = 2000000000;
long long doubled = static_cast<long long>(total) * 2;
std::cout << "doubled: " << doubled << '\n';
return 0;
}The output shows the correct value.
doubled: 4000000000Off-by-one errors
The classic is using the less-than-or-equal where the less-than was meant.
#include <iostream>
int main() {
int stock[5] = {10, 20, 30, 40, 50};
int count = 5;
int total = 0;
for (int i = 0; i <= count; ++i) { // reads stock[5], past the end
total += stock[i];
}
std::cout << "total: " << total << '\n';
return 0;
}And a habit that prevents the bug is to write the range as a half-open interval in a comment, or to use a range-based for whenever the index is not needed.
#include <iostream>
int main() {
int stock[5] = {10, 20, 30, 40, 50};
int total = 0;
for (int value : stock) {
total += value;
}
std::cout << "total: " << total << '\n';
return 0;
}The output is correct.
total: 150The accidental copy
Passing a large object by value when a reference was intended copies it on every call, and for a type that owns a resource it can also change the ownership meaning.
#include <iostream>
#include <string>
class Label {
public:
explicit Label(std::string text) : text_(std::move(text)) {
std::cout << "copy made\n";
}
const std::string& text() const { return text_; }
private:
std::string text_;
};
void print_label(Label label) { // by value: a copy every call
std::cout << label.text() << '\n';
}
void print_label_ref(const Label& label) { // by const reference: no copy
std::cout << label.text() << '\n';
}
int main() {
Label label("perishable");
print_label(label);
print_label_ref(label);
return 0;
}The output shows the extra copy.
copy made
perishable
perishableOwnership confusion in a class
A class that holds a raw pointer without saying whether it owns the thing that it points at is a design smell that leads to the leaks and the double frees.
#include <iostream>
#include <memory>
class Session {
public:
explicit Session(std::unique_ptr<int> id) : id_(std::move(id)) {}
~Session() = default;
Session(const Session&) = delete;
Session& operator=(const Session&) = delete;
int id() const { return *id_; }
private:
std::unique_ptr<int> id_;
};
int main() {
auto id = std::make_unique<int>(4821);
Session session(std::move(id));
std::cout << "session id: " << session.id() << '\n';
return 0;
}The output shows the session owning its identifier.
session id: 4821A review checklist
- Does any function return a reference or a pointer to a local?
- Does any iterator survive a change to the size of its container?
- Could any of the arithmetic overflow the type that it is using?
- Is every loop bound right, and is it less-than or less-than-or-equal?
- Are the big objects passed by a const reference rather than by value?
- Does every class that owns something say so, with a smart pointer or with the rule of zero?
Quick reference
- Never return a reference to a local. Return by value.
- Never use an iterator after the container may have reallocated.
- The signed overflow is
undefined, so you use the wider type. - The loop bound of n elements is usually the less-than and not the less-than-or-equal.
- You pass the big objects by a const reference.
- You say who owns the memory, and the smart pointer says it for you.
Try it yourself: take one of your own files and look for each of the six problems in the checklist. Then write the small version of the dangling reference and run it under the address sanitizer, and watch it report the use-after-free at the exact line.