Crash in string::assign

  • Follow


Here is the code


#include <vector>
#include <string>

using namespace std;

struct Pkt{
    int i;
    string s;
};

int main()
{
    vector<Pkt> v;
    v.reserve(1);
    v[0].s.assign("pankaj");
}

It is crashing on the last line and I can't figure out why. From what
I understand v.reserve(1) creates a default constructed struct and
pushes it in the vector. assign() then tries to modify the default-
constructed string inside that struct, but I can't think of a reason
for this to crash. Please help

{ v.reserve(1) doesn't construct v[0], v.size() still remains zero,
  and v[0] is a dangling reference. v.resize(1) does construct v[0].
  -mod/sk }

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply dragoncoder 9/21/2010 10:34:30 PM

On 22 Sep., 06:34, dragoncoder <pktiw...@gmail.com> wrote:
> Here is the code
>
> #include <vector>
> #include <string>
>
> using namespace std;
>
> struct Pkt{
>     int i;
>     string s;
>
> };
>
> int main()
> {
>     vector<Pkt> v;
>     v.reserve(1);
>     v[0].s.assign("pankaj");
>
> }
>
> It is crashing on the last line and I can't figure out why. From what
> I understand v.reserve(1) creates a default constructed struct and
> pushes it in the vector.

This misconception is the source of the wrong code. The
reserve function does guarantee that sufficient memory will
be allocated at this point to be able to hold the corresponding
number of container elements. But this is just does *not*
change the size of the vector nor does it allow to access
any elements beyond the current size (which is still 0 at
the point above). A precondition of invoking the operator[]
overload in std::vector is that the index is less than size(),
which is not satisfied above.

> assign() then tries to modify the default-
> constructed string inside that struct, but I can't think of a reason
> for this to crash. Please help

If you wanted to *resize* the vector, just call the member function
resize instead of reserve. You could also construct the vector
from begin with with a given size as in

vector<Pkt> v(1);

This will also ensure that the container has now one value-initialized
element, i.e. a size of 1.

HTH & Greetings from Bremen,

Daniel Kr�gler

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply ISO 9/23/2010 3:41:05 AM


1 Replies
434 Views

(page loaded in 0.057 seconds)

Similiar Articles:













7/25/2012 3:18:30 PM


Reply: