开发者

Random crash on access to my std::list<string> object

开发者 https://www.devze.com 2023-01-26 16:09 出处:网络
I have been getting random crashes when trying to access my std::list<string> object and can\'t figure out why it happens.

I have been getting random crashes when trying to access my std::list<string> object and can't figure out why it happens.

I started out with an extern vector<string> object but I've created a class for accessing it now, use a list instead (not that it matters but probably more appropriate for what I need it for) and make use of critical section just to be sure, however it didn't help any.

When I was using a vector I had crashes when calling size(). Using critical section or not has the same effect. I am hoping someone can point me in th开发者_运维技巧e right direction.

Thank you! The code:


class CWordHandler
{
public:
 void AddWord(string text);
 void DeleteWord(unsigned index);
 string ReadWord(unsigned index);
 void ClearWords();
 unsigned GetSize();

private: list<string> WordContainer; }; extern CWordHandler WordHandler; // ---------------------------------- string CWordHandler::ReadWord(unsigned index) { list<string>::iterator it = WordContainer.begin(); // crash advance(it, index); return index >= 0 && index <= WordContainer.size() ? *it : 0; }


Don't see how begin() can really crash, unless the list is hopelessly messed up on entry to this code.

Your error check needs to happen before you call advance, which will malfunction if given a range that is invalid.

list<string>::iterator it = WordContainer.begin(); // crash
if (index >= 0 && index <= WordContainer.size())
{
  advance(it, index);
  return *it;
} 
return 0;

The wisdom of returning a string constructed from 0 on error seems questionable to me. Perhaps a bool return and a string& parameter would be preferable.

Docs for advance say:

The range advanced through must be nonsingular, where the iterators must be dereferenceable or past the end.


Correction:

string CWordHandler::ReadWord(unsigned index)
{
 if (index >= WordContainer.size()) return 0;
 list<string>::iterator it = WordContainer.begin();
 advance(it, index);
 return *it;
}

Sorry for the format.

0

精彩评论

暂无评论...
验证码 换一张
取 消