By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,852 Members | 2,116 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,852 IT Pros & Developers. It's quick & easy.

Error on reallocation of a vector

P: 1
Hi, all... I have a problem when trying to reallocate a vector for a second time inside a loop.
The order is somelike:

for (n=k; n<L; n++)
{
vector.resize(n, (long) 0);
...

vector.clear(); //[Or alternativelly vector.resize(1);]
}

The loop first loop is executed appropriatelly, but after first increment of n, i get a crash of the heap... (when trying to resize the vector again... with n-zeros)

Has anyone any idea?

Thanks
Aug 14 '07 #1
Share this Question
Share on Google+
2 Replies


P: 16
I don't see why this shouldn't work, assuming of course that your vector is an std::vector<T>, where T is a built-in type (like int or long).

However, if your T is a class-type, the program may crash because the destructor is called on an uninitialized object.
Aug 14 '07 #2

P: 16
However, if your T is a class-type, the program may crash because the destructor is called on an uninitialized object.
Slight correction: If your T is a class-type the program may crash because the destructor is called on an object that was not properly copy-constructed.

If your T contains pointers (and a dtor), chances are you also need to make a copy ctor (and assignment operator) that properly creates a deep copy of your object, because vector uses the copy ctor internally.

Otherwise your T's dtor's will end freeing the same memory twice, which may easily cause the error you describe.
Aug 14 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.