0

I am working on a lexer and when I run the test program, I keep getting this error:

Segmentation fault

I read about the error and I am pretty sure that I am trying to write read only memory. This is my code:

#include <bits/stdc++.h>
#include <iostream>

using namespace std;

vector <string> split(string line) {
  vector <string> tokens;
  stringstream check1(line);
  string intermediate;

  while(getline(check1, intermediate, ';')) {
    tokens.push_back(intermediate + ";");
  }
  return tokens;
}

vector <vector<string>> lex(vector <string> tokens) {
  vector <vector<string>> lexed;
  lexed[0] = tokens;
  string token;
  for (int i = 0; i < tokens.size(); i++) {
    token = tokens[i];
    cout << token;
  }
  return lexed;
}

int main() {
  string line = "print(32); print(54); print(432);";
  vector <string> tokens = split(line);
  vector <vector<string>> x = lex(tokens);
  for(int i = 0; i < tokens.size(); i++) {
    cout << tokens[0][i] << "\n";
  }
}

Please help!

Jack Davis
  • 13
  • 2
  • 2
    `vector > lexed; lexed[0] = tokens;` is wrong – KamilCuk Apr 20 '20 at 20:48
  • segmentation fault = you are reading memory that you can't read (in poor words)... the "why"... is the same definition – Alberto Sinigaglia Apr 20 '20 at 20:48
  • Does this answer your question? [What is a segmentation fault?](https://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault) – Aykhan Hagverdili Apr 20 '20 at 20:49
  • If you used `at()` instead of `[ ]` to access your vector elements, you would have gotten a `std::out_of_range` exception thrown at the offending `at()` call instead of a seg fault, thus making it easier for you to debug the problem. For example [here is your program using at()](http://coliru.stacked-crooked.com/a/2e2fd599da201bce) – PaulMcKenzie Apr 20 '20 at 20:51
  • Using it along side `#include ` suggests that you do not know what `#include ` does. Before you use anything in C++ you should [familiarize yourself with its purpose and how to use it](https://stackoverflow.com/questions/25311011/how-does-include-bits-stdc-h-work-in-c). But in this case [you're better off not directly using it at all](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h). – user4581301 Apr 20 '20 at 22:03

1 Answers1

2

There are many many causes of segfaults. Yours is here

vector <vector<string>> lexed;
lexed[0] = tokens;

lexed has zero size, so lexed[0] is an error, and likely to cause a segfault.

This would work

vector <vector<string>> lexed;
lexed.push_back(tokens);
john
  • 85,011
  • 4
  • 57
  • 81