2013-10-30 119 views
0

我宣布我的头文件中像这样的数组:C++ Segfault,我不知道为什么?

private: 
    int frames[10]; 

而且在类的构造函数分配了类似这样的值:

file.open(File); 
if(file.is_open()) 
{ 
    std::string line; 
    getline(file, line); 
    std::string param[10]; 
    std::stringstream stream(line); 
    int n=0; 
    while(!stream.eof()) 
    { 
     getline(stream, param[n], '$'); 
     frames[n] = atoi(param[n].c_str()); 
     n++; 
    } 
    file.close(); 
} 

这个阵列上后来在一个函数:

currentFrame++; 
if(frames[currentAnimation] <= currentFrame) 
{ 
    currentFrame = 0; 
} 

当我运行我运行我的代码我得到分段错误,gdb返回此:

Program received signal SIGSEGV, Segmentation fault. 
0x0000000000402c22 in Sprite::update (this=0x7ffff6efe678 <main_arena+88>) at Sprite.cpp:93 93    
if(frames[currentAnimation] <= currentFrame) 
(gdb) bt 
#0 0x0000000000402c22 in Sprite::update (this=0x7ffff6efe678 <main_arena+88>) at Sprite.cpp:93 
#1 0x0000000000401fcb in main (argc=1, argv=0x7fffffffeb88) at main.cpp:146 

我不确定我要去哪里错,我认为这个错误在这里。 我真的不能发布所有的代码作为它的很多,但如果你需要更多 具体信息请直接询问。

非常感谢您提前。

+2

你如何确保'ñ<10'或'currentAnimation <10'?最有可能你被界访问了调用未定义的行为。 –

+2

我猜框架[currentAnimation]引用数组外 – Ashalynd

+2

你试过打印出你使用的索引吗? –

回答

3

试试这个

private: 
    std::vector<int> frames; 


file.open(File); 
if(file.is_open()) 
{ 
    std::string line; 
    getline(file, line); 
    std::string param; 
    std::stringstream stream(line); 
    while(getline(stream, param, '$')) 
     frames.push_back(atoi(param.c_str())); 
    file.close(); 
} 

currentFrame++; 
if(currentAnimation < frames.size() && frames[currentAnimation] <= currentFrame) 
{ 
    currentFrame = 0; 
} 

See Loki's answer for why while(!stream.eof()) is bad

+0

谢谢你这个工作,但仍然不明白为什么我的没有。 – user2936306

+0

@ user2936306:因为你的代码假设只有10个输入项(因此当n> = 10时,'param [n]'和'frames [n]'失败)。此代码对输入大小没有限制。 –

+0

@DieterLücking更新,谢谢 –

0

int n=0; 
while(!stream.eof() && n < 10) 
{ 

...

currentFrame++; 
if(currentFrame < 10 && frames[currentAnimation] <= currentFrame) 
{ 
    currentFrame = 0; 
} 

或使用类似

currentFrame = (currentFrame + 1) % 10; 
0

几个问题:

你只有10个项目在这里:

std::string param[10]; 

但没有检查你10:

while(!stream.eof()) 

所以这可能会增加10多个,这肯定会造成问题。

而且这种形式的循环几乎总是错的:

while(!stream.eof()) 
{ 
    getline(stream, param[n], '$'); 
    frames[n] = atoi(param[n].c_str()); 
    n++; 
} 

如果你在你输入的任何错误数据,这将进入一个无限循环。否则,当您到达EOF时,std::getline()无法读取数据并设置eof标志,但您仍然分配给帧(并增加n)。 atoi()对不良数据返回0,因此Frames中的最后一个元素将为零(不确定这是否是预期的行为(但其草率)

正确的样式是将读取放入while条件。这两个东西放在一起,你循环应该是这样的。

while(n < 10 && getline(stream, param[n], '$')) 
{ 
    // loop is only entered if the read succeed. 

    // Not sure about the type of `frames` so hard to talk about 
    // if this loop is still correct. The meaning has changed slightly. 
    frames[n] = atoi(param[n].c_str()); 
    n++; 
} 
if (n < 10) {/*We have an issue with not enough data!*/} 
相关问题