I wrote an application using wxWidgets that uses wxList. I am having some random crahses (segfault) in the destructors that collect the list data. I could not find a definite way of removing items from the list (Erase() VS DeleteNode()). Even iterating over the items has two flavours (list->GetFirst() VS list->begin()).
Below is a test class showing the approach I am using in my application. The test runs perfectly, no crash. It seems like some pointers are being used after they are freed, but I can not tell that by looking at the code. I suppose am doing something wrong around the Erase() and DeleteContents() calls.
P.S: in the application, the list contains about 15 thousand items, as opposed to only 9 in the test.
#include <wx/list.h>
#include <wx/log.h>
class TestItem
{
public:
TestItem(int _x, int _y) { x = _x; y = _y; }
int x;
int y;
};
WX_DECLARE_LIST(TestItem, TestList);
#include <wx/listimpl.cpp>
WX_DEFINE_LIST(TestList);
class Test {
public:
TestList *list;
Test() {
list = new TestList;
}
~Test() {
Clean();
delete list;
}
void CreateAndAddToList(int x, int y) {
TestItem *item = new TestItem(x, y);
list->Append(item);
}
void PrintAll() {
wxLogMessage(wxT("List size: %d"), list->GetCount());
wxTestListNode *node = list->GetFirst();
while (node) {
TestItem *item = node->GetData();
wxLogMessage(wxT("Item: %d, %d"), item->x, item->y);
node = node->GetNext();
}
}
void DeleteAllX(int x) {
wxTestListNode *node = list->GetFirst();
while (node) {
TestItem *item = node->GetData();
if (item->x != x) {
node = node->GetNext();
continue;
}
wxTestListNode *toDelete = node;
node = node->GetNext();
wxLogMessage(wxT("Deleting item: %d, %d"), item->x, item->y);
list->Erase(toDelete);
delete item;
}
}
void Clean() {
list->DeleteContents(true);
list->Clear();
}
static void DoAllTests() {
Test *t = new Test;
t->CreateAndAddToList(1, 1);
t->CreateAndAddToList(1, 2);
t->CreateAndAddToList(1, 3);
t->CreateAndAddToList(2, 1);
t->CreateAndAddToList(2, 2);
t->CreateAndAddToList(2, 3);
t->CreateAndAddToList(3, 1);
t->CreateAndAddToList(3, 2);
t->CreateAndAddToList(3, 3);
t->PrintAll();
t->DeleteAllX(2);
t->PrintAll();
t->Clean();
t->PrintAll();
delete t;
}
};