[英]I am getting segmentation fault. I have made the code to see if the brackets are balanced or not. C++
我編寫了這段代碼來檢查表達式中的平衡括號。 我已經使用了堆棧的鏈表實現。 我收到分段錯誤。 請首先解釋為什么我們會遇到分段錯誤,我是新手,很難理解分段錯誤和內存管理的概念。
#include <iostream>
using namespace std;
struct stack {
char data;
struct stack *next;
};
struct stack *top = NULL;
void push(char data) {
struct stack *temp = (struct stack *)malloc(sizeof(struct stack));
temp->data = data;
temp->next = top;
top = temp;
return;
}
void pop() {
struct stack *temp = top;
top = top->next;
return;
}
int isEmpty() {
if (top == NULL)
return 1;
else
return 0;
}
int main() {
int i = 0;
char array[250];
cout << "Enter code and end with $ sign : " << endl;
cin.getline(array, 250, '$');
while (array[i] != '\n') {
if (array[i] == '{' || array[i] == '[' || array[i] == '(') {
push(array[i]);
} else if (array[i] == '}' || array[i] == ']' || array[i] == ')') {
if (array[i] == '}' && top->data == '{')
pop();
else if (array[i] == ']' && top->data == '[')
pop();
else if (array[i] == ')' && top->data == '(')
pop();
else {
cout << "Not Balanced" << endl;
return 0;
}
}
i++;
}
if (isEmpty() == 1)
cout << "Balanced" << endl;
else
cout << "Not Balanced" << endl;
return 0;
}
因此,我將首先解釋分段錯誤的含義及其發生的原因。 當程序嘗試讀取不允許讀取的內存時,會發生分段錯誤。 如果您嘗試獲取已分配數組之外的數組元素,則可能會發生這種情況,如果您取消引用空指針,也會發生這種情況。
我認為您的問題可能是您的循環未能在正確的位置結束並最終訪問分配的 250 個空間之外的數組元素。 根據這個參考http://www.cplusplus.com/reference/istream/istream/getline/ , getline() 實際上並沒有將換行符包含到數組中,但是它總是附加一個空字符 '\\0'。
嘗試將while(array[i]!='\\n')
更改為while(array[i]!='\\0')
並告訴我是否可以解決問題。 如果沒有,我將繼續尋找更多錯誤。 您的代碼不是超級可讀,並且有很多地方可能會出錯。 我建議在您的每個函數之間添加空行。
此外,正如 molbdnilo 提到的,如果你有太多的右大括號,你也會得到一個分段錯誤,因為在這種情況下 top 將等於 null 並且你的程序將嘗試在你的條件下使用top->data
取消引用 top
我還注意到您使用了很多 C 約定,例如 struct、malloc() 和 NULL。 它工作正常,但請確保認識到 C 和 C++ 之間存在差異,並在學習時盡量堅持使用 C++ 源代碼,以免混淆。 祝你好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.