I have segfaults!

Today is my first time using c++ in a while. I am normally a python programmer. I keep getting segfaults and I've isolated it to the commented lines. (the ones that are commented cause segfaults when uncommented.)

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#include "defaultfile.h"

int main()
{
    ifstream mapin;
    string map;
    string s;
    int i = 0;
    while (i<=22){i++;top[i][0]="__";i++;};i=0;
    while (i<=21){i++;frw[i][0]="/";i++;};i=0;
    while (i<=21){i++;bck[i][0]="";i++;};i=0;
    //while (i<=45){i++;spc[i][0]=" ";i++;};i=0;
    //while (i<=112){i++;spc[i][1]="n";i++;};i=0;
    while (i<=22){i++;cout<<top[i][1]<<endl;i++;};i=0;
    while (i<=21){i++;cout<<frw[i][1]<<endl;i++;};i=0;
    while (i<=21){i++;cout<<bck[i][1]<<endl;i++;};i=0;
    //while (i<=45){i++;cout<<spc[i][1]<<endl;i++;};i=0;
    ...
}

the header is:

string top[23][3] = 
{{"", "", ""},
...
{"", "", ""}};
string frw[22][3] = 
{{"", "", ""},
...
{"", "", ""}};
string bck[22][3] = 
{{"", "", ""},
...
{"", "", ""}};
string spc[46][3] = 
{{"", "", ""},
...
{"", "", ""}};

Edit: Thank you. It's always the stupid things that I miss and spend an hour trying to find. All I needed was someone else to point it out.


while (i<=112){i++;spc[i][1]="n";i++;};i=0;

您将spc定义为:

string spc[46][3]

您将spc一直索引到112,但只有0-45对第一个索引有效。


Arrays are 0 based. You are writing over the end on each one of them. It crashed on spc because it's the last one. On the other ones you write into the memory of the following one.

To clarify: You do while (i <= 45) { i++; spc[i] ... while (i <= 45) { i++; spc[i] ... Now if i is 45 then you increment it to 46 and you access spc[46] which is outside of the bounds. Same for all the other lines.

Furthermore you only initialize every second field - not sure if that is intentional.

链接地址: http://www.djcxy.com/p/43886.html

上一篇: 具有未定义结果的C代码,编译器会生成无效代码(使用

下一篇: 我有segfaults!