簡體   English   中英

打印樹時出現分段錯誤(SIGSEGV)

[英]Getting Segmentation Fault (SIGSEGV) while printing tree

我試圖解決這個問題

https://practice.geeksforgeeks.org/problems/construct-an-expression-tree/1?utm_source=gfgpractice#

問題:為給定的后綴表達式創建表達式樹

我的方法:我嘗試維護一堆節點並使用通用后綴評估方法生成一棵樹,其中給定運算符的結果將是節點本身,但具有修改的左右指針。

但我遇到了錯誤。

Segmentation Fault (SIGSEGV)
Learn More about
Seg Fault
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;

struct et
{
    char value;
    et* left, *right;
    
    et(char x){
        value = x;
        left = right = NULL;
    }
};

bool isOperator(char c)
{
    if (c == '+' || c == '-' ||
            c == '*' || c == '/' ||
            c == '^')
        return true;
    return false;
}

void inorder(et *t)
{
    if(t)
    {
        inorder(t->left);
        printf("%c ", t->value);
        inorder(t->right);
    }
}

et* constructTree(char []);

int main()
{   
    int t;
    cin>>t;
    while(t--){
    char postfix[25];
    cin>>postfix;
    et* r = constructTree(postfix);
    inorder(r);
    cout<<endl;
}
return 0;
}// } Driver Code Ends


/*struct et
{
    char value;
    et* left, *right;
};*/

//function to construct expression tree
et* constructTree(char postfix[])
{
//code here
    stack<et> operand;
    et *root=NULL;
    for(int i=0;postfix[i] != '\0';++i){
        if(postfix[i]>='a' && postfix[i]<='z'){
            et node = et(postfix[i]);
            //cout<<node.value<<" "<<node.left<<" "<<node.right<<"\n";
            operand.push(node);
            /*et nod = operand.top();
            cout<<nod.value<<" "<<nod.left<<" "<<nod.right<<"\n";
            operand.pop();
            operand.push(nod);
            et *no = &(operand.top());
            cout<<no->value<<" "<<no->left<<" "<<no->right<<'\n';*/
        }
        else{
            et right1=operand.top();
            operand.pop();
            et left1=operand.top();
            operand.pop();
            et node = (et(postfix[i]));
            node.left = &left1;
            node.right= &right1;
            operand.push(node);
            root=&(operand.top());
            //cout<<node.value<<" "<<node.left<<" "<<node.right<<"\n";
            //inorder(root);
        }
    }
    //root=NULL;
    return root;
}

誰能告訴我該怎么做才不會出錯?

問題在這里node.left = &left1;

left1是一個局部變量,將被銷毀。 所以在那之后你訪問了一個無效的地址。

您可以使用類似這樣的東西node.left = new er(left1);

但是您應該首先將指針存儲在堆棧中。

在 function constructTree樹中,您不執行任何動態 memory 分配。 So whatever memory pointer you return from that function, is pointing to an invalid memory by the time you're outside the function.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM