0
votes

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.

4
Why are you initializing the strings like that?flight
Off-topic tip: Spaces and line breaks are your friend!Ates Goral
So, what is your question? Your code obviously overruns your arrays. Are you asking why overrunning array bounds causes segfault? Or are you asking something else?AnT

4 Answers

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

You defined spc as:

string spc[46][3]
1
votes

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

1
votes

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.

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

This will segfault on spc[46] for sure.