0

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.

Vitruvius
  • 3
  • 2

4 Answers4

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

You defined spc as:

string spc[46][3]
Brian Roach
  • 76,169
  • 12
  • 136
  • 161
1

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

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
1

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.

ChrisWue
  • 18,612
  • 4
  • 58
  • 83
  • Good catch on incrementing `i` before using it, and actually twice per loop. (On the other hand, that also means `i == 45` in the loop condition is impossible, however `top[23]` will get used in error) – Ben Voigt Mar 20 '11 at 17:43
0
//while (i<=112){i++;spc[i][1]="n";i++;};i=0;

This will segfault on spc[46] for sure.

corsiKa
  • 81,495
  • 25
  • 153
  • 204