So i’m getting a Segmentation fault: 11 error and I know which block is causing it, but i’m trying to understand why.
std::vector<Entity> grassEntities;
for (int i = 0; i < 40; i++) {
grassEntities.push_back(Entity(i * 32, 592, grassTexture));
}
std::vector<Entity> dirtEntities;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 41; j++) {
dirtEntities.push_back(Entity(j * 32, (688 - (i * 32)), dirtTexture));
}
}
bool gameRunning = true;
SDL_Event event;
while (gameRunning) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT)
gameRunning = false;
}
window.clear();
std::vector<Entity>::iterator it;
std::vector<Entity>::iterator it2;
for (it = dirtEntities.end(); it >= dirtEntities.begin(); it--){
window.render(*it);
}
for (it2 = grassEntities.end(); it2 >= grassEntities.begin(); it2--){
window.render(*it2);
}
window.display();
}
this issue lies with this section
for (it2 = grassEntities.end(); it2 >= grassEntities.begin(); it2--){
window.render(*it2);
}
which for me is odd because this section seemed to work just fine:
for (it = dirtEntities.end(); it >= dirtEntities.begin(); it--){
window.render(*it);
}
>Solution :
Inside the game loop, in the first iteration of both for loops, it is equal to dirtEntities.end() and it2 is equal to grassEntities.end(). Dereferencing end iterators is undefined behaviour. The fact that the code doesn’t crash is just "lucky".
If you want to iterate in reverse, use reverse iterators instead:
for (auto it = dirtEntities.rbegin(); it != dirtEntities.rend(); it++){
window.render(*it);
}
for (auto it2 = grassEntities.rbegin(); it2 != grassEntities.rend(); it2++){
window.render(*it2);
}