c++ std::vector.insert crashes on debug but works on release

My program crashes on this line but only in debug build, it works fine in release build.

m_lstIds.insert(m_lstIds.begin() + indexInsert, ID);

'm_lstIds' is a std::vector of int, 'ID' is an int. When the program crashed, m_lstIds had 3 items (1, 2, 3). indexInsert was '0' and ID was '0'.

The error message says:

Expression: vector iterator + offset out of range

I am running visual studio 2010; I am guessing it has something to do with bad project settings which conflicted with STL optimization.

Edit: When I said: "works on release" I meant if I do std::cout<<m_lstIds[i] for i = 0..3, I will actually get 0,1,2,3 printed out. In debug build it just crashes when I try to insert.

Edit2: I found the answer! Thanks everyone for the help.

Here is the shortest repro. The problem is the memset function I call at the constructor. Because the constructor of m_lstItem was called before the memset, it will erase whatever data in the vector that allowed insert to work properly.

What's really interesting is how this worked in release but not in debug. Would be great if someone can explain that part.

struct SimpleList
{
  SimpleList()
  {
    memset(this, 0, sizeof(SimpleList));
    m_lstItem.push_back(0);
    m_lstItem.push_back(1);
    m_lstItem.push_back(2);
  }

  void Crash()
  {
    m_lstItem.insert(m_lstItem.begin() + 0, 3);
  }

  std::vector<int>m_lstItem;
};

int main(int argc, char** argv[])
{ 
  SimpleList sl;
  sl.Crash();
  return 0;
}

Answers


memset(this, 0, sizeof(SimpleList)); is unsafe when your struct is not a POD.

Due to the member std::vector<int>m_lstItem;, your struct is not a POD.

Therefor, using memset is unsafe in this case, and leads to undefined behaviour. In other words: anything is allowed to happen! And anything includes working as expected...

My advice: Do not use memset in C++ unless you totally know what you are doing.


Need Your Help

AWS: free 3rd level DNS name to access EC2 instance

amazon-web-services amazon-ec2 dns

When I start EC2 instance it receives public new DNS name like ec2-xx-xx-xx-xx.compute-1.amazonaws.com.

Jquery/Javascript Calculation: not getting desired answer

javascript jquery

I'm to AutoCalculate Materials for Consumption...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.