Have a look at this snippet:
#include <string>
#include <iostream>
#include <vector>
using namespace std;
class base {
public:
string foo;
base() {};
base(const base &orig) {
this->foo = orig.foo;
};
~base() {} ;
};
class derived : public base {
public:
string bar;
derived(const derived &orig) : base(orig) {
this->bar = orig.bar;
}
derived() : base() {} ;
~derived() {};
};
void asd(derived d)
{
// works fine
cout << d.foo << d.bar << endl;
}
int main(void)
{
vector<derived> v;
derived bla;
bla.foo = "Test ";
bla.bar = "String ";
v.push_back(bla);
asd(bla);
// Why the hell does v.end()->foo and v.end()->bar segfault?!
cout << v.end()->foo;
cout << v.end()->bar << endl;
}
Why do I get an segmentation fault? This is the console output
(compiled with g++ -o test test.cpp -g)
./test
Test String
zsh: segmentation fault ./test
The this pointer of the class derived v.end() does not point to the correct position…
But why?
end()is not an iterator pointing to the last element. It points to one past the last element. Dereferencingend()is illegal.Use
back()if you want the last element.