【发布时间】:2015-08-25 14:35:17
【问题描述】:
目前正在我的游戏服务器上工作。当玩家在尸体对象的矩形上方时发送消息以使用特定物品时会发生此异常。
此代码发生在一个名为“Match”的对象中,该对象包含玩家和尸体的完整列表。
一分钟后我的对象就好了,我可以读取它所有的变量值,没有垃圾值。然后突然之间,我无法读取我所在对象中的任何内存。无缘无故。这最终会导致访问冲突异常。
当玩家发送使用物品消息时,调用该函数:
void Player::use_res(){
myMatch->res_corpse_under_player(this);
}
我将我想检查的玩家是否在尸体上交给 Match 对象中的这个函数。所以现在我们在匹配对象中。以下是该事件发生的三个函数,它们位于 Match.cpp 中:
bool intersect_inmatch(SFRECTANGLE a, SFRECTANGLE b){
if (a.left < b.right && b.left < a.right && a.top < b.bottom)
return b.top < a.bottom;
else
return false;
}
//Find the corpse that's undernearth this player
//corpse loop exception fix attempt
Corpse* Match::find_corpse_under_player(Player* player){
bool intersection = false;
SFRECTANGLE prect = player->getPRECT();
std::list<Corpse>::iterator cit;
cit = corpses.begin();
while(cit != corpses.end()){
SFRECTANGLE crect;
crect.left = cit->x;
crect.top = cit->y;
crect.right = cit->x + cit->mask.getSize().x;
crect.bottom = cit->y + cit->mask.getSize().y;
intersection = intersect_inmatch(prect, crect);
if(intersection){
return &(*cit);
}
++cit;
}
return NULL;
}
void Match::res_corpse_under_player(Player* player){
cout << "res corpse match function call" << endl;
Corpse* c = find_corpse_under_player(player);
if(c != NULL){
cout << "found corpse" << endl;
cout << "corpse name: " << c->name << endl;
if(c->thisPlayer != NULL){
cout << "this player: " << c->thisPlayer->name << endl;
}
}
}
我对其进行了调试,并且该对象在此行之后似乎无法访问其自身的任何内存:
intersection = intersect_inmatch(prect, crect);
这个函数是我尝试查看矩形是否重叠的地方。 这是调试的图片: http://i.imgur.com/M4yphMO.png
我尝试进入 intersect_inmatch(...) 调用,但由于某种原因,调试器指向这一行:
crect.bottom = cit->y + cit->mask.getSize().y;
然后又重新指向这一行:
intersection = intersect_inmatch(prect, crect);
我尝试再次踏入它,但现在它越过了它。之后,该对象似乎无法读取其任何内存(图中的步骤 3)。我不知道为什么会这样。什么可能是这样做的?我已经醒了 6 个小时试图找出原因,但我找不到原因。
异常发生在这一行:
cout thisPlayer->name
Server.exe 中 0x696C40F6 (msvcp110.dll) 处未处理的异常:0xC0000005:访问冲突读取位置 0x00000000。
编辑: 这是我最初创建尸体对象并将其推送到我的 Match 对象中的列表的地方:
//Player.cpp
Player::make_corpse_out_of_this_player(){
Corpse corpse(x, y, this); //this == instance of Player, setting Player* thisPlayer pointer to this in Corpse object.
corpse.name = string(name);
corpse.mask = mask;
myMatchPointer->corpses.push_back(corpse);
}
【问题讨论】:
-
也许
c->thisPlayer->name是NULL?此外,intersect_inmatch应该只是return a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom;。 (以这种方式分离测试是没有意义的。) -
看起来 c->thisPlayer->name 为 NULL?
-
看起来您正在尝试调试优化的构建。将其关闭以查看
intersect_inmatch中发生的情况。 -
您确定
find_corpse_under_player返回一个指向有效对象的指针吗?它可能在此之前很久就失效了。 (使用指向列表元素的指针是对未定义行为的公开邀请,除非您非常小心。) -
David Schwartz,当我输出 c->thisPlayer->name 时,它完全是空白的。但问题是,如果你看图片,整个 Match(“this”)对象无法读取它自己的任何内存。为什么?为什么它不能自己阅读? tsuki,我不知道你的意思是什么?使用 Visual Studio 2012 Express。我该如何关闭它? molbdnilo,是的,它正在返回一个有效的对象。然而,此时代码中的尸体对象中的指针不为空,但我无法显示名称:pastebin.com/xcYc6Eqn 是的,我设置了它的名称。只有当我尝试访问它并计算它时。
标签: c++ object memory call access-violation