SEGFAULT与STD :: getline一起使用定界线
Segfault from std::getline with delimiter
几个小时,我一直在尝试修复此segfault。该代码在第500次迭代之后总是发送Sigsegv。这是我一直在使用的test.csv。一次while循环击中第二组AMU值,Getline立即崩溃了该程序。我已经梳理了这一点,找不到可以挽救生命的问题。
值得注意的注意:我无法在每台机器上重现此错误!绝对有些记忆会被弄糊,但我只是无法弄清楚!
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <climits>
using namespace std;
int main(int argc, char **argv)
{
ifstream data;
data.open("TEST.csv", ifstream::in);
float amudata[505];
//initialize amudata
for (int x = 0; x < 505; x++) amudata[x] = INT_MIN;
std::string line;
//toss out the first 137 lines of config data
for (int x = 0; x < 137; x++)
{
std::getline(data, line);
}
//debug iteration counter
int x = 0;
//toss out the first part of the timestamp
//this is where SEGV happens
while (std::getline(data, line, ' '))
{
x++;
//toss out second part of timestamp
getline(data, line, ',');
//read and store the index, which is amu times 10
std::getline(data, line, ',');
int index = std::atof(line.c_str()) * 10;
//read and store the amu intensity
std::getline(data, line, ',');
float intensity = std::atof(line.c_str());
//some debug output
cout << index << " " << intensity << " ";
cout << line << " " << x << endl;
//keep track of only the maximum intensities
if (amudata[index] < intensity)
{
amudata[index] = intensity;
}
}
for (int x = 0; x < 505; x++)
{
printf("%fn", amudata[x]);
}
data.close();
return 0;
}
您的amudata
数组太小。
处理此行后您的程序崩溃:
2016/11/23 16:49:06.146, 50.500, -3.6263e-010,
当您这样做:
int index = std::atof(line.c_str()) * 10;
line
是"50.500"
,因此设置index = 505
。那你做:
amudata[index] = intensity;
但是amudata
的允许索引是从0
到504
,因此您是在数组边界之外编写的,这会导致不确定的行为。
您需要:
float amudata[506];
//initialize amudata
for (int x = 0; x < 506; x++) amudata[x] = INT_MIN;
最好不要在程序中像魔术数字一样传播魔术数字,使用常数或宏。
相关文章:
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 如何将enable-if与模板参数和参数包一起使用
- 如何将PERF_AMPLE_READ与mmap一起使用
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 在基于范围的for循环中使用结构化绑定声明
- 使用 LuaBridge 将 LuaJIT 绑定到C++会导致"PANIC: unprotected error"
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- 如何将重新绑定与自定义分配器和自定义列表一起使用
- CodeBlocks字符串输出定界线
- 使用C 从定界线拆分字符串中提取整数数组
- SEGFAULT与STD :: getline一起使用定界线
- 如何使用泛型在 C# 中将类型静态绑定在一起(如在 TypeToType <T>中)?
- boost::与boost:asio绑定在一起.boost::绑定后续
- boost::与boost:asio绑定在一起.boost::绑定不起作用,从示例中复制
- boost::将 asio 与 accepter.async_accept 一起使用时出现绑定错误
- C++将此指针与 lambda 函数中的绑定一起使用
- Clang:将绑定或mem_fn与字符串::c_str和转换一起使用时出现问题
- 如何将Boost::asio::buffer(buf,size)与Boost绑定一起使用
- 与模板模板类一起使用的自定义模板参数绑定器
- 将C++绑定与GObject Introspection一起使用