因此,我试图对基于数组的堆栈进行排序,但是我一直遇到以下问题:a.out(11849,0x115ce05c0)malloc: *对象0x7fc181402a80的错误:未分配释放的指针 a.out(11849,0x115ce05c0)malloc:* 在malloc_error_break中设置一个断点进行调试。 这是我的课程说明
StackType::StackType()
{
maxLength = 10;
Top = -1;
numArray = new int[maxLength];
}
//checks if stack is full
bool StackType::isFull()
{
if(Top == maxLength -1)
return true;
else
return false;
}
//checks if stack is empty
bool StackType::isEmpty()
{
if(Top == -1)
return true;
else
return false;
}
//insert numbers into stack
void StackType::push(int num)
{
if(isFull())
throw FullStack();
Top++;
numArray[Top] = num;
}
//deletes numbers in stack
void StackType::pop()
{
if(isEmpty())
throw EmptyStack();
Top--;
}
//returns number at the top pf the stack
int StackType::top()
{
if(isEmpty())
throw EmptyStack();
return numArray[Top];
}
//prints stack
void StackType::printStack()
{
if(isEmpty())
cout << "Stack is empty\n";
else
{
int tempIndex = 0;
//top is the last position of array
cout << "Printing stack:\n";
while(tempIndex <= Top)
{
cout << numArray[tempIndex] << endl;
tempIndex++;
}
}
}
//deletes array
StackType::~StackType()
{
delete [] numArray;
}
这是我的客户代码
#include "StackType.h"
#include <iostream>
using namespace std;
StackType sortStack(StackType stack, StackType &tempStack);
int main ()
{
//read 10 ints into stack
//output them first
StackType currentStack, orderedStack;
currentStack.push(21);
currentStack.push(49);
currentStack.push(7);
currentStack.push(81);
currentStack.push(5);
currentStack.push(17);
currentStack.push(2);
currentStack.push(26);
currentStack.push(42);
currentStack.push(58);
currentStack.printStack();
cout << "The following is the sorted stack\n";
sortStack(currentStack, orderedStack);
//implement recursion here
//output stack again
return 0;
}
StackType sortStack(StackType stack, StackType &tempStack)
{
int current;
if(stack.isEmpty() && tempStack.isFull()) {
cout << "did it \n";
return tempStack;
}
else
{
current = stack.top();
stack.pop();
if(tempStack.isEmpty())
{
cout << "here1 \n";
tempStack.push(current);
return sortStack(stack, tempStack);
}
else
{
if(current < tempStack.top())
{
stack.push(tempStack.top());
tempStack.pop();
tempStack.push(current);
cout << "here2 \n";
return sortStack(stack, tempStack);
}
else
{
//when current is greater than temp.top
tempStack.push(current);
cout << "here3 \n";
return sortStack(stack, tempStack);
}
}
}
}
答案 0 :(得分:2)
您按值传递StackType
,这将导致它被复制,但是您没有提供复制构造函数。结果,您最终得到两个StackType
实例,它们都指向同一数组,并且都试图删除它。第一个成功,另一个触发未定义的行为。
换句话说,您的课程违反了the Rule of Three/Five/Zero