Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Every few attempts to run my build, I get a segmentation fault. I dont understand why

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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);
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading