Bad_alloc problem
my program throws a std::bad_alloc开发者_运维知识库. After debugging it, I found out it is thrown in code
curFinalBucket->points.push_back(p);
where points is a vector<PPointT>
. Before the code line, curFinalBucket
is initialized as follows.
PFinalBucket curFinalBucket;
curFinalBucket = (FinalBucket*)malloc(sizeof(FinalBucket));
Strange thing is that if I simply put the above code in main
, no exception. But when I put it as follows,
void mergeBucket(map<BucketT, vector<PPointT>, Comp> *pMap, IntT numFinalBuckets)
{
...
PFinalBucket curFinalBucket;
curFinalBucket = (FinalBucket*)malloc(sizeof(FinalBucket));
curFinalBucket->points.push_back(p);
}
int testLoadBalancedLSH(IntT num_fbuckets, RealT avgNumPossessedTerms, IntT np, IntT d, char* dataFile)
{
...
mergeBucket(&mapstore, num_fbuckets);
}
int main(int nargs, char **args) {
...
testLoadBalancedLSH(atoi(args[1]), 0.01 * atoi(args[2]), atoi(args[2]), atoi(args[3]), args[4]);
}
it will throw the exception in question. Any ideas what this could be all about? thanks in advance.
I think the problem is you are creating curFinalBucket with malloc. This does not call the constructor so the internal vector<PPointT>
is not initialized when you try to use it.
I guess FinalBucket is something like:
class FinalBucket{
public:
vector<PPointT> points;
}
points
needs an initialization that is not happening because FinalBucket constructor is not being called and vector<PPointT>
constructor is not being called either.
You are just allocating memory, but you need the constructors to be called for initialization to take place.
The only way around this is to use new to allocate FinalBucket.
PFinalBucket curFinalBucket;
curFinalBucket = new FinalBucket();
curFinalBucket->points.push_back(p);
(FinalBucket*)malloc(sizeof(FinalBucket));
allocates memory for an object of the size of a FinalBucket
, but it doesn't actually create a final bucket. You should use new FinalBucket()
for this.
Also, as a note on style, hiding pointers behind macros/typedefs like PFinalBucket
makes your code harder to read. Just write FinalBucket *
instead, it's much clearer.
You should use new FinalBucket to allocate dynamic memory instead of malloc. The new operator will call the constructor of FinalBucket, in which vector which be initialized.
精彩评论