gpt4 book ai didi

c++ - ***检测到 glibc*** 免费(): invalid pointer:

转载 作者:太空宇宙 更新时间:2023-11-04 16:30:40 26 4
gpt4 key购买 nike

当我尝试运行我的代码时,标题中出现错误...这是我正在运行的

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;
}

瓦尔格林德:

==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)

看起来很蠢,但我一辈子都弄不明白,谢谢你的帮助

最佳答案

问题可能是因为在构造函数中你动态分配了一个数组:

queue = new tile[cap]; 

但在 deque 中,您使用非数组删除运算符将其删除。

tile* victim = queue;
queue++;
delete victim;

只是看起来代码中的逻辑不匹配。一方面,有分配动态数组的代码,但在其他地方,它删除了动态分配数组的各个元素。

关于c++ - ***检测到 glibc*** 免费(): invalid pointer:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7424613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com