data structures - [C++]Memory error thrown at destructor that wasn't there before this code. Trying to make a new dynamic array and populate it -


i working on lab dealing queues, don't think entirely relevant. task create "priority queue" , best way think of follows

void intqueue::enqueue(int num,int priorityofentry) {        if (isfull())         cout << "the queue full.\n";     else     {            // calculate new rear position         //insert correct lab code here haha         if (priorityofentry == 1)         {                rear = (rear + 1) % queuesize;             queuearray[rear] = num;             queuesize++;         }            else if (priorityofentry == 2)         {                 queuesize++;              int* newarray = new int[queuesize];             newarray[0] = num;              for(int counter = 0;counter< queuesize; counter++)             {                    newarray[counter+1] = queuearray[counter];             }                 queuearray = newarray;              delete [] newarray;          }            else cout << "invalid priority" << endl;          // insert new item           // update item count         numitems++;       }    }    

i have 2 priority levels, 1 , 2, explain in main program. when have equal priority of course works fine, when bump on in priority throws error @ destructor.

i don't think right way approach lab, seems work.. @ least if can memory error fixed. figure problem in change address of destructor thinks delete.. thought pointers kind of account that. understand need learn debug own programs. do. stare @ code , there nothing brick wall there. guess that's nudge in right direction for.

queuearray dangling pointer after this:

  queuearray = newarray; // both 'queuearray' , 'newarray' point                          // same memory after assignment.    delete [] newarray; 

as memory queuearray pointing has been deleted. attempt access or destroy queuearray accessing memory has been destroyed. correct order is:

delete[] queuearray; queuearray = newarray; 

additionally, there potential out-of-bounds access in for loop performs copying:

for(int counter = 0;counter< queuesize; counter++) {     // when 'counter == queuesize - 1'     // 'newarray[counter + 1]' 1 past end.     newarray[counter+1] = queuearray[counter]; } 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -