Bad_alloc exception when using new for a struct c++
- by bsg
Hi,
I am writing a query processor which allocates large amounts of memory and tries to find matching documents. Whenever I find a match, I create a structure to hold two variables describing the document and add it to a priority queue. Since there is no way of knowing how many times I will do this, I tried creating my structs dynamically using new. When I pop a struct off the priority queue, the queue (STL priority queue implementation) is supposed to call the object's destructor. My struct code has no destructor, so I assume a default destructor is called in that case.
However, the very first time that I try to create a DOC struct, I get the following error:
Unhandled exception at 0x7c812afb in QueryProcessor.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0012f5dc..
I don't understand what's happening - have I used up so much memory that the heap is full? It doesn't seem likely. And it's not as if I've even used that pointer before.
So: first of all, what am I doing that's causing the error, and secondly, will the following code work more than once? Do I need to have a separate pointer for each struct created, or can I re-use the same temporary pointer and assume that the queue will keep a pointer to each struct?
Here is my code:
struct DOC{
int docid;
double rank;
public:
DOC()
{
docid = 0;
rank = 0.0;
}
DOC(int num, double ranking)
{
docid = num;
rank = ranking;
}
bool operator>( const DOC & d ) const {
return rank > d.rank;
}
bool operator<( const DOC & d ) const {
return rank < d.rank;
}
};
//a lot of processing goes on here; when a matching document is found, I do this:
rank = calculateRanking(table, num);
//if the heap is not full, create a DOC struct with the docid and rank and add it to the heap
if(q.size() < 20)
{
doc = new DOC(num, rank);
q.push(*doc);
doc = NULL;
}
//if the heap is full, but the new rank is greater than the
//smallest element in the min heap, remove the current smallest element
//and add the new one to the heap
else if(rank > q.top().rank)
{
q.pop();
cout << "pushing doc on to queue" << endl;
doc = new DOC(num, rank);
q.push(*doc);
}
Thank you very much, bsg.