c++ - 写入文件时核心转储?

标签 c++ segmentation-fault coredump

您好,这是我为 C++ 文件 i/o 练习编写的一段非常简单的代码。但是当我运行它时,我得到了一个 Segmentation Fault (core dumped) 异常。 下面是我的代码:

# include <iostream>
# include <string>
# include <cmath>
# include <fstream>
using namespace std;

int main()
{
double num, rad, i, angle, x, y;
char * filename;
ofstream file;
// prompt  ask for number
cout << "Enter the number of sample points: ";
cin >> num;

// prompt for circle radius.
cout << "Enter the circle radius: ";
cin >> rad;

// prompt for output file name.
cout << "Enter the output filename: ";
cin >> filename;

file.open (filename, fstream :: in | fstream :: trunc);
if(!file.is_open())
{
    cout << "Error opening file " << filename << endl;
    cout << "Exiting..." << endl;
    return 0;
}
for(i = 1; i <= num; i ++)
{
    //angle = 2 * M_PI * (i/num);
    //x = rad * cos(angle);
    //y = rad * sin(angle);
    //file << "\t" << x << "\t" << y << endl;
    file << "this is " << i << endl;
}
cout << "finished";
file.close();
return 0;
}

我不确定问题出在哪里,但在输入输出文件名后出现错误消息“seg fault (core dumped)”。

谢谢

最佳答案

cin >> filename 将是未定义的行为,因为 filename 是一个未初始化的指针。

如果要存储字符,需要为其分配空间。所以你可以这样做:

char filename[150] = {0};
cin >> filename; // OK, you provide space for 149 characters. Will still break
                 // if more characters are provided by the user.

或:

#include <string>
std::string filename; // overloads operators >> and << with streams
                      // automatically performs memory management
// std::cin >> filename; /* Would stop at first space */
std::getline(std::cin, filename); // better: will stop at any carriage return

关于c++ - 写入文件时核心转储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9124320/

相关文章:

c++ - 停止消息 _WIN32_WINNT 未定义。默认为 _WIN32_WINNT_MAXVER(参见 WinSDKVer.h)

c++ - 如何告诉c++编译器对象在别处没有改变以达到更好的优化

ios - 为什么dyld_decache segfault的解决方案有效?

c - 我不明白为什么会收到 "Segmentation fault (core dumped)"错误

c - 使用 mmap 将文件读取为字符串

c++ - 跟踪/断点陷阱(核心转储)Gtkmm

c++ - 如何使用 Eclipse 在 Linux 上调试 C++ 程序?

c++ - 非 const 左值引用

无法在 C 程序中打开 16 个文件(核心转储)

c - *** 检测到 glibc *** ./shell : double free or corruption (top)---Aborted (core dumped)