Skip to content

C++ 失败图谱

一份面向真实调试时间的失败手册。每个条目都包含最小可复现程序、工具应当给出的输出,以及去掉该失败所需的最小修复。

这不是“未定义行为冷知识”清单。本页每个 broken/fixed 对都会由 tools/verify_failure_claims.py 在 CI 中编译并执行。如果编译器或 sanitizer 不再产生预期失败,构建就会失败。因此这里记录的是被测试过的声明,而不是“应该会怎样”的散文。

怎么读一个条目

  • 症状——崩溃、卡死或错误结果出现时,你看到什么。
  • 错误版本——能稳定复现失败的最小程序。
  • 工具输出——验证器要求在 sanitizer 输出里找到的标记。
  • 修复版本——去掉该失败所需的最小改动。
  • 练习——关联的街机 Boss 或实验。

单独运行一个条目:

python3 tools/verify_failure_claims.py --id use-after-free

验证器默认使用 g++(可用 CXX 覆盖),并打印真正测试过的编译器版本。CI 运行同一个脚本,所以页面不会悄悄和代码脱节。

1. 释放后使用

症状——指针看起来仍然有效,但它指向的对象已经销毁。调试构建里这次读取可能成功,换一个分配器或在负载下就崩了。

错误版本

#include <iostream>

int main() {
    int* value = new int(42);
    delete value;
    std::cout << *value << '\n';
}

工具输出——heap-use-after-free

修复版本

#include <iostream>
#include <memory>

int main() {
    auto value = std::make_unique<int>(42);
    std::cout << *value << '\n';
}

为什么修复有效——所有权变得明确。整数的生命周期与 unique_ptr 完全一致,也不存在能活过它的第二个指针。

练习——悬垂指针 Boss。

2. 迭代器失效

症状——创建迭代器时它还是有效的,随后容器重新分配;再解引用时,它指向已经释放的存储。

错误版本

#include <iostream>
#include <vector>

int main() {
    std::vector<int> values{1, 2, 3};
    auto it = values.begin();
    values.push_back(4);
    std::cout << *it << '\n';
}

工具输出——attempt to dereference a singular iterator

修复版本

#include <iostream>
#include <vector>

int main() {
    std::vector<int> values{1, 2, 3};
    values.reserve(4);
    auto it = values.begin();
    values.push_back(4);
    std::cout << *it << '\n';
}

为什么修复有效——reserve 在取迭代器之前就为第四个元素留好了容量,所以 push_back 不会重新分配。reserve 只是对容量的承诺,不是“可以跨任意修改保留迭代器”的许可证;大小不确定时应该用下标或重新查找。

练习——迭代器失效 Boss。

3. 数据竞争

症状——答案每次运行都不一样;一个线程的写入丢失,或者只有 sanitizer 恰好观察到两次访问时才报告竞争。

错误版本

#include <iostream>
#include <thread>

int counter = 0;

void increment() {
    for (int i = 0; i < 100000; ++i) {
        ++counter;
    }
}

int main() {
    std::thread first(increment);
    std::thread second(increment);
    first.join();
    second.join();
    std::cout << counter << '\n';
}

工具输出——ThreadSanitizer: data race

修复版本

#include <atomic>
#include <iostream>
#include <thread>

std::atomic<int> counter{0};

void increment() {
    for (int i = 0; i < 100000; ++i) {
        counter.fetch_add(1, std::memory_order_relaxed);
    }
}

int main() {
    std::thread first(increment);
    std::thread second(increment);
    first.join();
    second.join();
    std::cout << counter.load() << '\n';
}

为什么修复有效——原子操作让“读—改—写”成为一个不可分割的操作。这个例子只需要原子性,所以 relaxed 顺序足够;它不需要约束其他内存操作的顺序。

练习——数据竞争 Boss。

4. 重复释放

症状——分配器看到同一块内存被归还两次。第二次 delete 可能立刻破坏堆,也可能在很久之后一个无关调用里才崩溃。

错误版本

#include <iostream>

int main() {
    int* value = new int(7);
    delete value;
    delete value;
    std::cout << "unreachable\n";
}

工具输出——attempting double-free

修复版本

#include <iostream>
#include <memory>

int main() {
    auto value = std::make_unique<int>(7);
    std::cout << *value << '\n';
}

为什么修复有效——所有权交给 unique_ptr,它只销毁对象一次,也不暴露第二次 delete 的机会。

练习——重复释放 Boss。

5. 堆越界

症状——下标写到了分配范围之外。小越界可能悄悄破坏下一个对象,大越界可能在很远的地方崩溃。

错误版本

#include <iostream>

int main() {
    int* values = new int[4]{};
    values[4] = 9;
    std::cout << values[3] << '\n';
    delete[] values;
}

工具输出——heap-buffer-overflow

修复版本

#include <iostream>
#include <vector>

int main() {
    std::vector<int> values(4);
    values.at(3) = 9;
    std::cout << values[3] << '\n';
}

为什么修复有效——.at() 检查下标,越界时抛出异常而不是继续写。std::vector 同时携带大小,所以合法范围在调用点就是已知的。

练习——生命周期实验。

6. 悬垂 string_view

症状——string_view 很便宜,因为它不拥有字符;这也是它的危险:拥有字符串的对象销毁后,view 仍然指向已释放的存储。

错误版本

#include <iostream>
#include <string>
#include <string_view>

int main() {
    auto* text = new std::string("temporary");
    std::string_view view = *text;
    delete text;
    std::cout << view << '\n';
}

工具输出——heap-use-after-free

修复版本

#include <iostream>
#include <string>
#include <string_view>

int main() {
    std::string text = "temporary";
    std::string_view view = text;
    std::cout << view << '\n';
}

为什么修复有效——字符串比 view 活得更久。经验规则是:string_view 应该作为函数参数,或者作为一个临时视图,并且它的拥有者在每次使用时都显然还活着。

练习——生命周期实验。

7. 通过非虚基类删除

症状——delete base 只调用基类析构函数,不调用派生类析构函数。派生资源泄漏,释放大小也可能不对。

错误版本

#include <iostream>

struct Base {
    ~Base() {}
};

struct Derived : Base {
    int* values = new int[4];
    ~Derived() { delete[] values; }
};

int main() {
    Base* base = new Derived;
    delete base;
    std::cout << "unreachable\n";
}

工具输出——new-delete-type-mismatch

修复版本

#include <iostream>
#include <vector>

struct Base {
    virtual ~Base() = default;
};

struct Derived : Base {
    std::vector<int> values{4};
};

int main() {
    Base* base = new Derived;
    delete base;
    std::cout << "destroyed\n";
}

为什么修复有效——虚析构函数会分派到最派生类的析构函数。修复同时把裸数组换成 vector,让派生对象自己管理存储,不再需要手写 delete[]。

练习——所有权与生命周期。

8. 非法向下转型

症状——static_cast 断言了一种并不存在的类型关系。程序随后按错误的类型布局读写对象。

错误版本

#include <iostream>

struct Base {
    virtual ~Base() = default;
};

struct A : Base {
    int a = 1;
};

struct B : Base {
    int b = 2;
};

int main() {
    Base* base = new A;
    auto* wrong = static_cast<B*>(base);
    wrong->b = 3;
    std::cout << wrong->b << '\n';
    delete base;
}

工具输出——downcast of address

修复版本

#include <iostream>

struct Base {
    virtual ~Base() = default;
};

struct A : Base {
    int a = 1;
};

struct B : Base {
    int b = 2;
};

int main() {
    Base* base = new A;
    auto* wrong = dynamic_cast<B*>(base);
    if (wrong != nullptr) {
        wrong->b = 3;
    }
    std::cout << (wrong == nullptr ? "not a B" : "a B") << '\n';
    delete base;
}

为什么修复有效——dynamic_cast 检查运行时类型;对象不是 B 时返回 nullptr。这个检查把失败路径显式化,而不是把错误假设变成内存破坏。

练习——所有权与生命周期。

验证整张图谱

在仓库根目录运行:

python3 tools/verify_failure_claims.py

脚本会把所有标记过的 broken/fixed 对编译到临时目录,用声明的 sanitizer 运行错误版本,检查预期标记,再运行修复版本并要求干净退出。

范围

这张图谱刻意保持很小。它覆盖八类可以在 Linux + GCC 上稳定演示的失败;它不是“程序没有未定义行为”的证明,也不能替代对真实应用运行 sanitizer。

如果编译器改变了错误文本,请同时更新标记和页面;如果某个失败不再复现,请删除该条目,而不是放宽检查。