leetcode c++ 设计循环队列 出现AddressSanitizer错误
题目网址:https://leetcode-cn.com/explo...
我的代码
#include<iostream>
using namespace std;
class MyCircularQueue {
private:
int tail = -1;
int head = -1;
int *p;
int len;
public:
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k) {
p = new int(k);
len = k;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value) {
if(this->isFull()){
return false;
}
if(this->tail == -1 && this->head == -1){
this->tail = 0;
this->head = 0;
p[0] = value;
}else{
tail+=1;
tail %= len;
p[tail] = value;
}
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue() {
if(this->isEmpty()){
return false;
}
if(head == tail && head != -1){
head = -1;
tail = -1;
}else{
head += 1;
head = head % len;
}
return true;
}
/** Get the front item from the queue. */
int Front() {
if(this->isEmpty()){
return -1;
}
return p[head];
}
/** Get the last item from the queue. */
int Rear() {
if(this->isEmpty()){
return -1;
}
return p[tail];
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty() {
return (tail == -1) && (head == -1);
}
/** Checks whether the circular queue is full or not. */
bool isFull() {
return (tail+1)%len == head;
}
void printValue(int len){
for(int i =0 ; i< len ;i++){
cout<<p[i]<<" ";
}
}
};
int main(){
int k = 3;
MyCircularQueue* obj = new MyCircularQueue(k);
cout<< obj->enQueue(1);
cout<< obj->enQueue(2);
cout<< obj->enQueue(3);
cout<< obj->enQueue(4);
cout<< obj->Rear(); // 返回 3
cout<< obj->isFull(); // 返回 true
cout<< obj->deQueue(); // 返回 true
cout<< obj->enQueue(4); // 返回 true
cout<< obj->Rear(); // 返回 4
obj->printValue(k);
return 0;
}
错误信息:执行错误信息:AddressSanitizer: heap-buffer-overflow on address 0x602000000074 at pc 0x0000003a1b5f bp 0x7ffd1fcc5f50 sp 0x7ffd1fcc5f48
最后执行的输入:["MyCircularQueue","enQueue","enQueue","enQueue","enQueue","Rear","isFull","deQueue","enQueue","Rear"] [[3],[1],[2],[3],[4],[],[],[],[4],[]]
跪求大佬帮助QAQ~~
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题出在你的 new 语句上,我知道你想做的是
new 一个数组出来
但实际你写的
只会 new 出一个 int 出来,并给这个 int 赋初值 k
然后你按k个int 去用,就把堆栈搞崩了。