简体   繁体   English

我收到分段错误。 我已经编写了代码来查看括号是否平衡。 C++

[英]I am getting segmentation fault. I have made the code to see if the brackets are balanced or not. C++

I have written this code to check for balanced brackets in an expression.我编写了这段代码来检查表达式中的平衡括号。 I have used linked list implementation of stacks.我已经使用了堆栈的链表实现。 I am getting a segmentation error.我收到分段错误。 Please explain why do we get segmentation error in the first place, I am newbie and having a hard time understanding the concept of segmentation errors and memory management in general.请首先解释为什么我们会遇到分段错误,我是新手,很难理解分段错误和内存管理的概念。

#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;
}

So I will begin by explaining what a segmentation fault means and why it happens.因此,我将首先解释分段错误的含义及其发生的原因。 A segmentation fault happens when a program tries to read memory that it's not allowed to read.当程序尝试读取不允许读取的内存时,会发生分段错误。 This can happen if you try to get an array element that is outside of the allocated array and it can also happen if you dereference a null pointer.如果您尝试获取已分配数组之外的数组元素,则可能会发生这种情况,如果您取消引用空指针,也会发生这种情况。

I think the problem in your case might be that your loop fails to end in the right place and ends up accessing array elements outside of the 250 spaces allocated.我认为您的问题可能是您的循环未能在正确的位置结束并最终访问分配的 250 个空间之外的数组元素。 according to this reference http://www.cplusplus.com/reference/istream/istream/getline/ , getline() doesn't actually include the newline character into the array, however it always appends a null character '\\0'.根据这个参考http://www.cplusplus.com/reference/istream/istream/getline/ , getline() 实际上并没有将换行符包含到数组中,但是它总是附加一个空字符 '\\0'。

Try changing while(array[i]!='\\n') to while(array[i]!='\\0') and let me know if that fixes it.尝试将while(array[i]!='\\n')更改为while(array[i]!='\\0')并告诉我是否可以解决问题。 If not I will keep looking for more errors.如果没有,我将继续寻找更多错误。 Your code is not super readable and there are a lot of places that something could go wrong.您的代码不是超级可读,并且有很多地方可能会出错。 I would recommend adding empty lines between each of your functions.我建议在您的每个函数之间添加空行。

Also, as molbdnilo mentioned, you will also get a segmentation fault if you have too many closing braces, since in this case top will be equal to null and your program will try to dereference top using top->data in your condition此外,正如 molbdnilo 提到的,如果你有太多的右大括号,你也会得到一个分段错误,因为在这种情况下 top 将等于 null 并且你的程序将尝试在你的条件下使用top->data取消引用 top

Also I notice you're using a lot of C conventions such as struct, malloc(), and NULL.我还注意到您使用了很多 C 约定,例如 struct、malloc() 和 NULL。 It works fine, but make sure to recognize that there is a difference between C and C++ and try to stick to C++ sources when learning so you don't get confused.它工作正常,但请确保认识到 C 和 C++ 之间存在差异,并在学习时尽量坚持使用 C++ 源代码,以免混淆。 Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM