如何修复C++程序随机崩溃?我的代码选选项后崩溃求助
问题排查与修复
你的程序崩溃核心原因是使用未初始化的野指针,直接解引用会触发内存访问违规:
具体问题点
main函数中char *opt是未初始化的指针,没有指向有效内存空间,cin >> opt会尝试将输入写入未知区域,直接导致崩溃。compile_program函数里的string *cppfile和string *outputfile同样是野指针,解引用cin >> *cppfile时会访问非法内存,引发程序崩溃。- 用
opt == "1"这种方式比较char*,实际是对比指针地址而非字符串内容,逻辑本身不成立。
修复后的代码
#include <iostream> #include <string> // 显式引入string头文件,保证跨编译器兼容性 using namespace std; void compile_program() { cout << "worked\n"; string cppfile; // 直接使用栈上的string对象,替代不安全的指针 string outputfile; cout << "FILENAME: "; cin >> cppfile; cout << "\nOUTPUT FILE: "; cin >> outputfile; cout << endl; string command = "g++ " + cppfile + " -o " + outputfile; system(command.c_str()); } int main() { while (true) { cout << "Welcome to the program loader.\n"; cout << "OPTION 1: Compile program\n"; cout << "OPTION 2: Run program\n"; cout << "> "; string opt; // 用string存储输入,避免指针相关问题 cin >> opt; cout << endl; // 直接比较string内容,逻辑正确 if (opt == "1" || opt == "a" || opt == "A") { compile_program(); } else if (opt == "2" || opt == "b" || opt == "B") { // run_program(); } } }
额外说明
- 移除不必要的指针,直接使用栈上
string对象,既保证内存安全又简化代码。 - 显式包含
<string>头文件,避免依赖编译器隐式引入导致的兼容性问题。 - 利用
string的==运算符比较内容,修正原char*指针地址对比的逻辑错误。
内容的提问来源于stack exchange,提问作者Hector Robertson
相关产品推荐
相关产品推荐

