I’m trying to make a little custom vector…
element class, should point to the adress of the next class but with this code
class foo {
private:
int attr;
public:
foo(){attr = 10;}
int get_attr(){return attr;}
void set_attr(int a){attr =a;}
};
class element_foo {
private:
foo data;
element_foo *ptr_next;
public:
element_foo(){ptr_next = NULL;}
element_foo(int dat){data.set_attr(dat); ptr_next = NULL;}
element_foo(int dat, element_foo next){
data.set_attr(dat);
ptr_next = &next;
}
foo get_data(){return data;}
element_foo get_next(){return *ptr_next;}
void print_array(){
if (ptr_next == NULL) {
std::cout<< data.get_attr()<<std::endl;
}
else {
std::cout<< data.get_attr()<<std::endl;
this->get_next().print_array();
}
}
};
int main (int argc, char * const argv[]) {
// insert code here...
element_foo a1(10);
element_foo a2(15,a1);
element_foo a3(20,a2);
a3.print_array();
std::cout << "Hello, World!\n";
return 0;
}
when I print a3, it get to segmentation fault… why? where is my mistake?
The error is in this constructor:
You are taking the address of a local.
ptr_next = &next;Once the function ends, the address is invalid.What you need to do is to pass
nextin as a pointer:And change your main to this:
EDIT:
Alternatively, you can just pass it by reference: