I get the error in the title when I try to run my code…
here’s what I’m running
class MyQueue {
tile* queue;
int size;
public:
MyQueue(int cap);
~MyQueue();
void enqueue(tile t);
tile dequeue();
bool isEmpty();
};
void MyQueue::enqueue(tile t) {
queue[size] = t;
size++;
}
tile MyQueue::dequeue() {
tile temp = queue[0];
tile* victim = queue;
queue++;
delete victim;
return temp;
}
bool MyQueue::isEmpty() {
if (size == 0)
return true;
else
return false;
}
MyQueue::MyQueue(int cap) {
queue = new tile[cap];
size = 0;
}
MyQueue::~MyQueue() {
delete[] queue;
}
int main(int argc, char *argv[]) {
tile tile1; tile1.type = '1';
tile tile2; tile2.type = '2';
tile tile3;
MyQueue q(10);
q.enqueue(tile1);
q.enqueue(tile2);
tile3 = q.dequeue();
cout<<tile3.type<<" =1?"<<endl;
return 0;
}
valgrind:
==4506== Mismatched free() / delete / delete []
==4506== at 0x4C27FFF: operator delete(void*) (vg_replace_malloc.c:387)
==4506== by 0x400CD2: MyQueue::dequeue() (MyQueue.h:37)
==4506== by 0x400DD7: main (p1.cpp:24)
==4506== Address 0x5964040 is 0 bytes inside a block of size 120 alloc'd
==4506== at 0x4C28658: operator new[](unsigned long) (vg_replace_malloc.c:305)
==4506== by 0x400D35: MyQueue::MyQueue(int) (MyQueue.h:49)
==4506== by 0x400D9F: main (p1.cpp:21)
==4506==
1 =1?
==4506== Invalid free() / delete / delete[]
==4506== at 0x4C27C7B: operator delete[](void*) (vg_replace_malloc.c:409)
==4506== by 0x400D74: MyQueue::~MyQueue() (MyQueue.h:54)
==4506== by 0x400E2F: main (p1.cpp:21)
==4506== Address 0x596404c is 12 bytes inside a block of size 120 free'd
==4506== at 0x4C27FFF: operator delete(void*) (vg_replace_malloc.c:387)
==4506== by 0x400CD2: MyQueue::dequeue() (MyQueue.h:37)
==4506== by 0x400DD7: main (p1.cpp:24)
==4506==
==4506==
==4506== HEAP SUMMARY:
==4506== in use at exit: 0 bytes in 0 blocks
==4506== total heap usage: 1 allocs, 2 frees, 120 bytes allocated
==4506==
==4506== All heap blocks were freed -- no leaks are possible
==4506==
==4506== For counts of detected and suppressed errors, rerun with: -v
==4506== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 4 from 4)
seems like something stupid but I can’t figure it out for the life of me, thanks for the help
The problem might be due to the fact that in the constructor you’re dynamically allocating an array:
but in
dequeyou delete it using the non-array delete operator.It just looks like the logic in the code is mismatched. On one hand there is code that allocates dynamic arrays but then in other places it deletes individual elements of that dynamically allocated array.