Re: Allocating vector of strings seem to crash. Allocating array of strings seems to be ok .
Rakesh Kumar wrote:
Hi All -
In a project of mine - I was trying to scale down the actual issue
to the following piece of code. I need to allocate an array of strings
and reserve the individual string to a particular size (4K) .
I wrote 2 functions - allocVectorOfStrings() and
allocArrayOfStrings().
Each of them seem to allocate similar amounts of memory - but the
version of vectorOfStrings seem to crash with the following error -
"double free or corruption (out): 0x08055ff8 ***" .
I was just curious if I am doing anything fundamentally wrong here
to cause the issue.
#include <iostream>
#include <cstdlib>
#include <vector>
void allocVectorOfStrings();
void allocArrayOfStrings();
void allocVectorOfStrings() {
std::vector<std::string> * vt = new std::vector<std::string>();
vt->reserve(50);
'reserve' does not construct vector's elements. It only allocates
memory for constructing them later, when 'insert' is used. Here
'*vt' does not contain _any strings_. It's empty. It's _capable_
of containing at least 50 without reallocation of its storage. But
it doesn't have any elements.
for (size_t i = 0; i < vt->capacity(); ++i) {
This is a very bad idea. Never iterate to capacity. Always
iterate to size.
std::cout << "We are probably ok" << i << "\n";
No, you're not OK.
vt->operator[](i).reserve(40);
You're accessing a non-existent element at the index 'i' and
then calls a member functions for it. Undefined behaviour.
}
delete vt;
}
void allocArrayOfStrings() {
std::string * vt = new std::string[4096];
Here 'vt' contains all 4096 elements.
for (size_t i = 0; i < 1024; ++i) {
std::cout << "We are probably ok" << i << "\n";
Yes, you are.
vt[i].reserve(4096);
'vt[i]' represents a real string. You can call 'reserve' for
it, no problem.
}
delete [] vt;
}
int main()
{
allocArrayOfStrings();
allocVectorOfStrings(); //This function crashes
return EXIT_SUCCESS;
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask