Сортировка стека с использованием рекурсии - PullRequest
0 голосов
/ 04 декабря 2018

Поэтому я пытаюсь отсортировать стек на основе массива, но у меня постоянно возникает следующая проблема: 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);


        }
    }
}
}

1 Ответ

0 голосов
/ 04 декабря 2018

Вы передаете StackType по значению, что приводит к его копированию, но вы не предоставили конструктор копирования.В результате вы получаете два экземпляра StackType, каждый из которых указывает на один и тот же массив, и оба пытаются удалить его.Первый успешен, другой вызывает неопределенное поведение.

Другими словами, ваш класс нарушает Правило трех / пяти / нуля

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...