C ++ STL列表函数使用空列表进行segfault [英] C++ STL list functions segfaulting with empty list
问题描述
我有一个指针列表作为类的成员。我实例化那个类,并且当列表为空时,诸如size()和empty()的各种函数会失败并显示segfault。当我添加的东西到列表中,他们很好。我试图抽象我在做一个测试文件,它的工作完美。这是我想我当我的代码失败时(虽然显然不是):
I have a list of pointers as a member of a class. I instantiate that class, and various functions such as size() and empty() fail with a segfault when the list is empty. When I add something to the list, they're fine. I tried to abstract what I'm doing with a test file, and it works perfectly. This is what I THINK I'm doing when my code fails (though am clearly not):
#include <list>
#include <iostream>
class Test {
int i;
};
int main() {
std::list<Test*> tlist;
if (tlist.empty()) {
std::cout << "List empty";
} else {
std::cout << "List not empty";
}
}
我不能真正发布整个代码清单导致的问题,因为它是相当大的和一堆文件,但会尝试直接粘贴所有相关的代码:
I can't really post the entire code listing that's causing the issue, as it's fairly large and over a bunch of files, but will try to paste all the relevant bits straight from code:
播放器中的类声明:
class Player : public ScreenObject {
private:
std::list<Thing*> inventory;
构造函数中没有对该列表进行任何操作。
Nothing is done to that list in the constructor.
失败的地方:
main.cpp:
Player pc(iname, w_choice, c_choice, 11, 11, WHITE, '@');
....
if (pc.addToInv(t)) {
currentLevel.delObject(id);
}
....
player.cpp:
player.cpp:
int Player::addToInv(Thing& t) {
if (inventory.size() <= 52) {
inventory.push_back(&t);
} else {
shiplog("Cannot add to inventory, 52 item limit reached",10);
return 0;
}
}
使用gdb运行时出现的错误发生在调用size(),并到此结束:
The error I get when running it with gdb occurs on the call to size(), and ends up here:
Program received signal SIGSEGV, Segmentation fault.
0x0804eda6 in std::_List_const_iterator<Thing*>::operator++ (this=0xbfff9500)
at /usr/include/c++/4.4/bits/stl_list.h:223
223 _M_node = _M_node->_M_next;
任何猜测都非常感激!
完整的追踪是:
(gdb) bt
0 0x0804e28a in std::_List_const_iterator<Thing*>::operator++ (
this=0xbfff9500) at /usr/include/c++/4.4/bits/stl_list.h:223
1 0x0804e64e in std::__distance<std::_List_const_iterator<Thing*> > (
__first=..., __last=...)
at /usr/include/c++/4.4/bits/stl_iterator_base_funcs.h:79
2 0x0804e4d3 in std::distance<std::_List_const_iterator<Thing*> > (
__first=..., __last=...)
at /usr/include/c++/4.4/bits/stl_iterator_base_funcs.h:114
3 0x0804e2e6 in std::list<Thing*, std::allocator<Thing*> >::size (
this=0xbffff244) at /usr/include/c++/4.4/bits/stl_list.h:805
4 0x0804df78 in Player::addToInv (this=0xbffff068, t=...) at player.cpp:551
5 0x0804a873 in main (argc=1, argv=0xbffff494) at main.cpp:182
推荐答案
int Player::addToInv(Thing& t) {
if (inventory.size() <= 52) {
inventory.push_back(&t);
} else {
shiplog("Cannot add to inventory, 52 item limit reached",10);
return 0;
}
}
通过引用传递,但其地址传递给inventory.push_back()。尝试只传递't'。
Thing is passed by reference, but then its address is passed to inventory.push_back(). Try just passing 't'.
这篇关于C ++ STL列表函数使用空列表进行segfault的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!