[英]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.