在 Linux 下用 C++ 避免程序崩溃,核心思路是:减少未定义行为、做好错误检查、合理使用防御性编程和调试工具。下面从常见原因到解决方案系统说明。
void func(int* p) {
if (!p) {
return; // 或记录日志
}
*p = 10;
}
✅ 建议:
#include <memory>
std::shared_ptr<int> p = std::make_shared<int>(10);
std::unique_ptr<int> up = std::make_unique<int>(20);
✅ 避免:
new / delete❌ 危险:
std::vector<int> v;
v[10] = 1; // 未定义行为
✅ 安全:
if (index < v.size()) {
v[index] = 1;
}
或用 at()(会抛异常):
v.at(index) = 1;
int x = 0;
std::string s;
❌ 不要:
int x;
try {
riskyFunction();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
} catch (...) {
std::cerr << "unknown exception" << std::endl;
}
✅ 建议:
class A {
public:
A() {
try {
init();
} catch (...) {
// 清理或记录
}
}
};
std::mutex m;
int value;
void add() {
std::lock_guard<std::mutex> lock(m);
++value;
}
✅ 工具:
std::mutexstd::atomic// 错误示例
delete pointer; // 另一个线程可能还在用
#include <signal.h>
#include <iostream>
void handler(int sig) {
std::cerr << "catch signal: " << sig << std::endl;
exit(1);
}
int main() {
signal(SIGSEGV, handler);
}
⚠️ 注意:
assert 仅用于调试#include <cassert>
assert(ptr != nullptr);
✅ 发布版本关闭:
-DNDEBUG
g++ -fsanitize=address -g main.cpp
✅ 能检测:
g++ -fsanitize=undefined -g main.cpp
valgrind ./a.out
gdb ./a.out core
bt
✅ 必须做
✅ 强烈建议
Linux C++ 不崩溃的秘诀:少写未定义行为 + 多检查 + 工具辅助。
如果你愿意,可以贴一段你经常崩溃的代码,我可以帮你具体指出问题并给出安全写法。