写入文件时转储的核心
Core dumped when writing to file?
嗨,这是我为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
请为文件名分配一些内存,您只能使用ponter。更改
char filename[50];
相关文章:
- 如何找出GDB的SIGTRAP核心转储的根本原因
- C++映射分割错误(核心转储)
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 浮点异常(核心转储)#694457
- 分段错误(核心转储)但无法弄清楚
- 链接到libkcapi时没有核心转储
- 分段错误(核心转储) - 使用 SavedModel 的 Tensorflow C++ API 进行推断
- 在基数排序中,我得到 munmap_chunk():无效指针和中止(核心转储).为什么?
- C++指针无法在函数外部传递值和分段错误(核心转储)错误
- 合并排序:分段错误核心转储
- C++:分段错误(核心转储)
- 从 pybind11 构建导入模块时出现"分段错误(核心转储)"
- 如何使用 lldb 在曼扎罗中调试 lz4 文件格式的核心转储?
- qt C++命令行代码中的分段错误(核心转储)
- 从文件中读取的数据,但发生核心转储错误
- googletest:测试基类具有纯虚拟方法的派生类时的核心转储
- C++ atof - 分段错误(核心转储)
- Linux C 只禁止我的程序使用核心转储
- 为什么我的代码包含错误分段错误(核心转储)?