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~~

阅读 2.3k
1 个回答

问题出在你的 new 语句上,我知道你想做的是

p = new int[k];

new 一个数组出来

但实际你写的

p = new int(k);

只会 new 出一个 int 出来,并给这个 int 赋初值 k

然后你按k个int 去用,就把堆栈搞崩了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题