Таким образом, цель моего кода состоит в том, чтобы иметь строку в качестве ввода, преобразовать ее в постфикс и прикрепить каждый символ постфикса к связанному списку.
Когда я запускаю свой код в Release it работает отлично, но когда я запускаю его в Debug, появляется следующая ошибка: выдается необработанное исключение: нарушение прав чтения. temp был 0xDD DDDDDD в функции печати LinkedList
Сообщение об ошибке в моем коде
Так что это мой основной метод
int main(int argc, char** argv) {
LinkedList list1 = postfix("a*b+c/d-e");
list1.print();
};
А это моя постфиксная функция
LinkedList postfix(string input) {
// Declare a stack with the capacity of 100 (it is just a large number)
Stack<char> myStack(100);
LinkedList returnList;
// The for loop check the charactors in the infix expressing
for (int i = 0; i < input.length(); i++) {
// If the charactor is an operand, we attach it to the LinkedList
if (input[i] >= 'a' && input[i] <= 'z') {
returnList.attach(input[i]);
}
// If the operator is an open paranthesis, we push it into the stack
else if (input[i] == '(') {
myStack.Push(input[i]);
}
else if (input[i] == ')') {
// If the stack is empty, it means there is no open paranthesis. It is an error, so we
// terminate the program
if (myStack.IsEmpty()) exit(0);
char topOP;
myStack.Pop(topOP);
// We keep pop the operators in the stack and attach them into the output Postfix string
while (topOP != '(') {
returnList.attach(topOP);
myStack.Pop(topOP);
// If we cannot find close parenthesis and the stack is empty, it is an error.
if (myStack.IsEmpty()) exit(0);
}
}
// If the charactor is an operator
else {
// Get the priority number of the incoming operator
int p = priority(input[i]);
// If the operator is not supported, we terminate the program
if (p == -1) exit(1);
// If there is no operator in the stack to compare, we just push the incoming
// operator into the stack
if (myStack.IsEmpty()) {
myStack.Push(input[i]);
}
else {
//we get the top operator
char topOP = myStack.Top();
//If the priority of the incoming operator is greater than the priority of the top operator
//we push it to the stack
if (p > priority(topOP)) {
myStack.Push(input[i]);
}
//if the priority of the incoming operator is less than or equal to the priority of the top operator
else {
//we traverse through the stack until its is empty or...
//the priority of incoming operator is less than the current operator
while (!myStack.IsEmpty() && p <= priority(topOP) ) {
myStack.Pop(topOP);
returnList.attach(topOP);
if (myStack.IsEmpty()) { break; }
topOP = myStack.Top();
}
//we push the the incoming operator when the loop finished
myStack.Push(input[i]);
}
}
}
}
// We attach the operators remainding in the stack to the linked list
while (!myStack.IsEmpty()) {
char topOP;
myStack.Pop(topOP);
returnList.attach(topOP);
}
return returnList;
}
Во время отладки я заметил, где моя ошибка была
В постфиксной функции переменная returnList, был совершенно в порядке, когда возвращался, а затем деструктор LinkedList выполнялся для уничтожения returnList
В моей основной функции я выровнял переменную list1 с постфиксом функции (который является возвращаемым значением). Во время отладки я заметил, что list1 заканчивался тоннами мусорных значений, которые я не понимал, потому что returnList (внутри моей функции postfix) завершился полностью хорошо
И, поскольку это возвращаемое значение, копия из returnList был сделан и затем он был назначен на list1, и после этого деструктор уничтожил returnList (когда функция закончилась)
Вот мой класс LinkedList
class LinkedList {
public:
// In the beginning, the linked list is empty, so we set first to NULL
LinkedList() {
first = last = NULL;
}
// We return the memory of all nodes in the linked list back to the system
~LinkedList() {
Node* temp = first;
while (temp) {
Node* prev = temp;
temp = temp->link;
delete prev;
}
}
// If first is pointing to NULL, it implies the linked list is empty
bool IsEmpty() { ... }
// This function attaches a new element to the end of the linked list
void attach(char newData) { ... }
void print() {
Node* temp = first;
while (temp) {
if (temp == last) {
cout << temp->data << endl;
temp = temp->link;
}
else {
cout << temp->data << " -> ";
temp = temp->link;
}
}
cout << endl;
}
private:
Node* first;
Node* last;
};
А вот и Node Класс
// This is the node of the linked list
class Node {
private:
char data;
// A poiter to the next node
Node* link;
// The class LinkedList will access the data in the class Node, so we declare
// the class LinkedList as a friend class
friend class LinkedList;
};
Так почему же происходит эта ошибка? И почему это происходит только в Debug, но не в Release
Любая помощь приветствуется
Заранее спасибо