Segfault during seemingly normal copy operation

closed account (jwC5fSEw)
I get a segfault here on line 29:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cctype>
using namespace std;

bool str_isalpha(string str) {
    for (unsigned i = 0; i < str.size(); ++i) {
        if (!isalpha(str[i])) return false;
    }
    return true;
}

int main() {
    ifstream in("records.txt");
    if (!in.is_open()){
        cerr << "whoops";
        return 1;
    }
    ofstream out("formatted_records.txt");
    vector<string> temp;
    vector<string> headers;
    string line;
    for (int i = 0; getline(in,line); ++i) {
        temp.push_back(line);
        static int k = -1;
        if (str_isalpha(temp[i])) {
            headers[++k] = temp[i];
            temp[i] = "\n";
        }
        else {
            temp[i] += "," + headers[k];
        }
    }
}


I'm not sure at all why. According to the debugger, temp[0] is the proper value right before the segfault, so I can't see why this isn't working. Any suggestions?
Perhaps the problem is located in line 33...
If the first string is not alpha you have an expression of headers[-1]

Initializing k to zero and using headers[k++] in line 29 could solve the problem I suppose...
Last edited on
closed account (jwC5fSEw)
It's not. I stepped through it and it always hit on line 29.

And that didn't fix anything (it also wouldn't work for my purposes).
Ah, I found it! You see, headers is an empty vector! The segfault is caused because you use operator[] on an empty vector! A way to fix this could be the following:

1
2
3
4
5
6
7
8
9
10
11
vector<string> temp;
vector<string> headers;
string line;
string tmp; //<-add this here

//...

//and use it like this
tmp=temp[i];
headers.push_back(tmp);
k++;


EDIT: Still, what I said in the first post is important! Don't forget to fix that problem too somehow...

EDIT 2: Or you could just do headers.push_back(temp[i]); k++; lol... I feel so stupid now...
Last edited on
Topic archived. No new replies allowed.