【发布时间】:2018-10-27 06:06:56
【问题描述】:
我正在编写一个基本的Asteroids 程序,使用SFML graphics library,并在调试程序时收到errors/crashes。这只发生在我试图通过空格键从我的船上发射"photon torpedo" 时。这是代码的sn-p。
//check for keypress
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Space) {
for (int index = 0; index < MAX_PHOTONS; index++) {
photons[index] = new SpaceObject(PHOTON_TORPEDO, PHOTON_RADIUS, ship->getLocation(), ship->getVelocity(), ship->getAngle())
photons[index]->applyThrust(PHOTON_SPEED);
std::cout << "LAUNCHING TORPEDO\n";
}
}
// update game objects ------------------------------------------
ship->updatePosition();
for (int index = 0; index < ARRAY_SIZE; index++) {
if (&asteroids[index] != NULL) {
asteroids[index]->updatePosition();
}
}
for (int index = 0; index < MAX_PHOTONS; index++) {
if (&photons[index] != NULL) {
photons[index]->updatePosition();
}
}
// draw new frame ------------------------------------------------
window.clear();
window.draw(background);
for (int index = 0; index < ARRAY_SIZE; index++) {
if (&asteroids[index] != NULL) {
asteroids[index]->draw(window);
}
}
for (int index = 0; index < MAX_PHOTONS; index++) {
if (&photons[index] != NULL) {
photons[index]->draw(window);
}
}
运行代码会导致瞬间崩溃,调试会导致:
polygons2.exe 中 0x00311746 处的未处理异常:0xC0000005:访问 违规读取位置0x00000018。
我相信错误在于按键事件。
【问题讨论】:
-
如果它会导致即时崩溃,那么您有一个 debugger 候选者成熟。该访问冲突强烈表明您正在取消引用指向某个结构的 NULL 指针,特别是该结构上 24 字节深的东西。使用调试器,你会发现你的问题。仅供参考,这个:
if (&asteroids[index] == NULL)完全没有意义。那个&符号不应该在那里。该错误在此代码中的多个位置重复出现。 -
&photons[index] != NULL始终为真。
标签: c++ pointers graphics logic sfml