Segmentation fault passing reference vector<string> into class member

Jun 21, 2019 at 5:19pm
So... this is my situation

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>
#include "foo.h"
using namespace std; 
int main(){
        *
        *
        *
foo *radice;
string root = "A";
vector<string> vettore = {"B","+","C"};

radice = radice->crea_circuito ( root, vettore );
        *
        *
        *
return 0;}


foo.h
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>
using namespace std;
class foo{
public:
       foo *crea_circuito ( string st, vector<string> & vettore );
private:
       vector<string>::iterator _tmp;

protected:
       string st;
};


foo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "foo.h"
        *
        *
        *
foo *foo::crea_circuito ( string st, vector<string> & vettore ) {
        cout << st << endl; //here print
	_tmp = vettore.begin(); //here segmentation fault
	cout<< *_tmp<<endl;
}
        *
        *
        *


i don't know why i have segmentation fault when i try to work with "vector<string> & vettore" inside member "crea_circuito".

Thanks for help!
Last edited on Jun 21, 2019 at 5:21pm
Jun 21, 2019 at 5:41pm
There isn't enough code to go on here.

We can't see how vettore is constructed and passed.

I can't even be certain the fault happens where you think it does. Is a debugger telling you that's the line?

If vettore is valid, that line shouldn't fail. That's why we must see the calling code.

My suspicion, however, is that the fault is actually happening on the next line, dereferencing _tmp, which would be expected if vettore is actually empty.
Jun 21, 2019 at 5:42pm
1
2
foo *radice; // uninitialized
radice = radice->crea_circuito( root, vettore );

You have invalid pointer.
You try to call the member function of a foo object, but your pointer does not point to a valid foo object.

If the pointer would point to a valid object, the statement makes it to point to somewhere else. What does the crea_circuito return? Who will remember the first foo?
Jun 21, 2019 at 5:48pm
You should #include <string> btw.

I ran it, got no segmentation fault. It ran just fine. You should also replace line 8 in "foo.h" with: vector<string>::const_iterator _tmp; If you don't plan on changing the values within the string, then best to use a pointer to const
Last edited on Jun 21, 2019 at 5:49pm
Topic archived. No new replies allowed.