Menu

Access violation using vector reserve

2008-03-18
2012-09-26
  • Matthew Phillips

    Hello,

    I don't understand how the problem I'm having is even possible--

    lines.reserve(3); //Access violation

    'lines' is a vector of structs ('Line'). It doesn't matter whether I use a vector<Line>::size_type object in place of '3', I get the same result.

    Crucially, 'lines' is not empty at this point--the first element has been assigned.

    The books I've looked at (e.g. Josuttis) have given me no indication that a post-assignment call to 'reserve' should be illegal--is it?

    I'm new to C++ (but not C, Matlab), and I have run into errors arising from sloppiness on my part with 'const'--could that have something to do with it?

    Again, if people have ideas as to how this error is even possible I would appreciate it (posting all my code seems like it would just cloud the issue at this point).

    Thanks--
    Best,
    Matt

     
    • Matthew Phillips

      Dear Clifford,

      You are too modest! The problem goes away if I pre-allocate a >= number of elements then I end up using. The 'Line' struct has a member which contains pointer members (actually it's a recursive type, even worse) so I am sure that deallocation has something to do with it. I had noticed that the problem went away with a larger preallocation earlier, but didn't understand why this helped. Tracing the error through the STL library appears to have confirmed things. Now I can go after the deeper problems in my code this episode reveals... Anyway, thanks.

      Best,
      Matt

       
    • cpns

      cpns - 2008-03-18

      > posting all my code seems like it would
      > just cloud the issue at this point

      What!? More than posting nothing!? We are not mind readers - what a dafty conclusion to have come to!

      You need not post all your code, simply create a small example of code that produces this error, if you cannot reproduce it that way, then it is definitely specific to your code and you will have little choice but to post it.

      Using reserve reallocates the vector and invalidates all previously obtained iterators, references and pointers to elements of the vector. If you have stored such a reference and later used it that would cause an error.

      Clifford

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.