开发者

I have segfaults!

开发者 https://www.devze.com 2023-02-18 17:57 出处:网络
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 whe

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] = 
{{"", "", ""},
...
{"", "", ""}};
s开发者_StackOverflow社区tring 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;

You defined spc as:

string spc[46][3]


You're indexing spc all the way up to 112, but only 0-45 are valid for the first index.


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] ... 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.


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

This will segfault on spc[46] for sure.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号