Note that there are some explanatory texts on larger screens.

plurals
  1. POBad_alloc exception when using new for a struct c++
    primarykey
    data
    text
    <p>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.</p> <p>However, the very first time that I try to create a DOC struct, I get the following error:</p> <p>Unhandled exception at 0x7c812afb in QueryProcessor.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0012f5dc.. </p> <p>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.</p> <p>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?</p> <p>Here is my code:</p> <pre><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&gt;( const DOC &amp; d ) const { return rank &gt; d.rank; } bool operator&lt;( const DOC &amp; d ) const { return rank &lt; d.rank; } }; //a lot of processing goes on here priority_queue&lt;DOC, std::vector&lt;DOC&gt;, std::greater&lt;DOC&gt;&gt; q; //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() &lt; 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 &gt; q.top().rank) { q.pop(); cout &lt;&lt; "pushing doc on to queue" &lt;&lt; endl; doc = new DOC(num, rank); q.push(*doc); } </code></pre> <p>Thank you very much, bsg.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload