对于我的类函数,我得到双重释放或损坏错误

I get the double free or corruption error , for my class functions

本文关键字:释放 错误 损坏 于我的 我的 类函数      更新时间:2023-10-16

这是我.cpp文件内容:

#include <iostream>
#include"1.h"
using namespace std;
Stack:: Stack(){
size=20;    
 a=new int[size];   
top=-1;
}
Stack::Stack (int si){
size=si;
a=new int[si];
top =-1;}
Stack::Stack(Stack& s){
a=new int[s.size];
for(int i=0 ; i<s.size; i++)
    a[i]=s.a[i];
size=s.size;
}
Stack::~Stack(){
delete [] a;
}
void Stack::Push(int data){
if(this->isfull())
    cout<<"stack is full!n";
else
    a[top++]=data;
}
int Stack::Pop(){
if(this->isempty())
    cout<<"stack is empty!n";
else
    return a[top--];
}
bool Stack::isempty(){
if(top==-1) 
     return true;
 else
    return false ;
}   
bool Stack::isfull(){
if(top==size-1 ) 
    return true ;
else
    return false ;
}
void Stack::Print(){
for(int i=top ; i>-1 ; i--)
    cout<<a[i]<<endl;
}
int main(){
Stack a(3);
a.Push(1);
a.Push(3);
cout<<a.Pop();
a.Push(5);
a.Push(7);
a.Print();  
return 0;
}

运行程序后,我收到以下错误: "./1"中的错误:双重释放或损坏(输出(:0x000000000240a010***已中止(核心已转储(我有复制构造函数和任何东西,我做什么?

  • 默认构造函数将 top 设置为 -1,因此Stack::Push(int) a[top++]=data;是未定义的行为(尝试写入 a[-1] ,这超出了数组边界(。 这是错误消息所指的损坏,只有在调用 delete [] a 时,标准库才会注意到它。 将其更改为 a[++top] = data;
  • 您的复制构造函数不会分配给top,使其值在副本中未初始化。 因此,从副本读取top是未定义的行为。
  • 您的复制构造函数应Stack(Stack const &) .
  • 您应该实现复制赋值运算符Stack & operator=(Stack const &);
当您

-1初始化top时,应该a[++top] a[top++],否则您将有越界访问权限,因此 UB。