Reputation: 887
If I reserve large amount of memory for a vector, (it will be filled out with data later on), can the memory reserved be used by others?
for example,
vector<double* > vD;
vD.reserve(30000000); // the number is less than the maximum size of a vector
... ...
for(int i=0; i< 1000000; i++)
{
double * pF = new double; // will be pushed back to the vector
... ...
vD.push_back(pF);
delete pF;
}
pF = NULL;
The code above just shows the idea. In the real code, double is an self-defined object which contains pointers. When I run the code, I got crashed with info: Free heap block 3bab8 modified at 3bacc after it was freed. The exact memory address(3bab8 and 3bacc ) will change. when I checked my vector:
for _First --- 0x28df0020
_Last 0x28df0870
_End 0x3ece3c20
For my understanding, the memory reserved for vD should go btw 0x28df0020 and 0x3ece3c20. If I understand this right, then the memory reserved is untouched. Am I right? Then why do I get heap block modified after it was freed? How should I deal with it? Thanks.
Upvotes: 0
Views: 98
Reputation: 103703
You're storing pointers to objects, then deleting those objects, thereby invalidating the pointers. The solution is to simply store objects, not pointers to objects.
vector<double> vD;
...
double pF;
...
vD.push_back(pF);
For cases where you must use pointers (e.g. polymorphic objects), use smart pointers.
vector<unique_ptr<Base>> vD;
...
unique_ptr<Base> pF(new Derived);
...
vD.push_back(move(pF));
The queries about reserve
are irrelevant to your problem, but to answer your question: No, once you've reserved space for your vector, others may not use it.
Upvotes: 2