首页 > 解决方案 > C++ SFML 数组错误:访问冲突读取位置 0xC0000005

问题描述

我正在使用 C++ 和 SFML 制作游戏,并且在使用数组渲染各种项目时遇到问题。当我尝试绘制一组精灵时,调试正常,没有警告和错误,但我的游戏程序只运行了 20 秒,然后它停止运行,并说,'未处理的异常在 0x7C50CF2E(sfml-graphics- d-2.dll),ECOVID-19 SFML.exe):0xC0000005:访问冲突读取位置 0xCCCCCCD0。我尽我所能,但我不知道为什么会发生这个异常。这是我怀疑错误原因的代码。尽管我的英语很差,但还是感谢您阅读。

 #include <SFML/Graphics.hpp>
 ...
 using namespace std;
 using namespace sf;
 ...

 int main () {
 ...

 //item Sprites

 Texture bombTex;
 bombTex.loadFromFile("images/bomb.png");
 Sprite bomb;
 ...
 Texture bomb2Tex;
 bomb2Tex.loadFromFile("images/bomb_2.png");
 Sprite bomb_2;
 ...
 Texture cakeTex;
 cakeTex.loadFromFile("images/cake.png");
 Sprite cake;
 ...
 Texture coffeeTex;
 coffeeTex.loadFromFile("images/coffee.png");
 Sprite coffee;
 ...
 Texture chickenTex;
 chickenTex.loadFromFile("images/chicken.png");
 Sprite chicken;
 ...
 Texture pizzaTex;
 pizzaTex.loadFromFile("images/pizza.png");
 Sprite pizza;

 //item array (I made an item array to display & render various items in the game screen.)
 Sprite item[10]; //Although I change the array size to 4 or 5, the same exception occurs.
 item[0] = bomb;
 item[1] = coffee;
 item[2] = bomb_2;
 item[3] = chicken;
 item[4] = pizza;

 std::vector<Sprite> items;
 items.push_back(Sprite(item[4]));

 ...

 while (window.isOpen())
 {   ...
     ...
  for (size_t i = 0; i < items.size(); i++)
  {
     if (humanArr[index].getGlobalBounds().intersects(item[i].getGlobalBounds())) 
     //humanArr[index] is a player Sprite.
      {
         ...
          items.erase(items.begin() + i);
       }
   }
   ...
  window.clear();
   ...
  for (size_t i = 0; i < items.size(); i++)
     {
         window.draw(item[i]); // <- the exception error occurs here.
      }

   ...
 window.display();
  }
 return 0;
}

标签: c++sfml

解决方案


可能发生的情况是,当您将 复制Sprite item[10];std::vector<Sprite> items;Sprite 类时,正在制作浅拷贝。这意味着如果 Sprite 类使用new运算符分配任何内存并将其存储在成员指针中,那么浅拷贝只会复制指针指向的地址。当你调用items.erase(items.begin() + i);Sprite 的析构函数时,它会被调用,并且在析构函数中它可能会在指向某个资源的指针中调用 delete。

当您调用window.draw(item[i]);该库时,该库将尝试使用该资源并找到一个无效地址。

我的建议是你不要使用Sprite item[10];and only the std::vector<Sprite> items;,像这样:

std::vector<Sprite> items;

items.push_back(bomb);
items.push_back(coffee);
...
window.draw(items[i]);

您不需要使用中间数组,只需std::vector<Sprite>;


推荐阅读