簡體   English   中英

分段錯誤 - 核心轉儲

[英]Segmentation Fault - Core dumped

這是我使用堆棧將表達式從后綴轉換為中綴的程序。 我沒有收到任何錯誤,但在運行時,編譯器說 Segmentation Fault - Core Dumped。 我認為這與指向垃圾值的指針有關。 我如何追蹤到這個流氓指針? 另外,有沒有更好的方法將后綴轉換為中綴?

#include<iostream>
#include<string.h>
#include<stdio.h>
#include<math.h>
class StringStack
{
    public:
    char arr[20][20];
    int top;
    StringStack()
    {top=-1; arr[20][20]={NULL};}
    void push(char* a)
    {strcpy(arr[++top],a);}
    char* pop()
    {return arr[top--];}
};
void paranthesise(char a[])
{
    int l = strlen(a);
    a[l+2] = '\0';
    for(int i=l; i>=0; i++)
        a[i] = a[i-1];
    a[0] = '(';
    a[l+1] = ')';

}
using namespace std;
int main()
{
    char temp[1];
    char postfix[20] = "";
    char temp2[10] = "";
    char temp3[10] = "";
    StringStack s1;
    cout<<"Enter Postfix Expression: "<<endl;
    gets(postfix); int l = strlen(postfix);
    for(int i=0; i<l;   i++)
    {
        if(postfix[i]!='*'&&postfix[i]!='/'&&postfix[i]!='+'&&postfix[i]!='-')
        {
            temp[0]=postfix[i];
            s1.push(temp);
        }
        else
        {
            strcpy(temp2,s1.pop());
            strcpy(temp3,s1.pop());
            switch(postfix[i])
            {
                case'*':
                    temp[0]='*'; break;
                case'/':
                    temp[0]='/'; break;
                case'+':
                    temp[0]='+'; break;
                case'-':
                    temp[0]='-'; break;

                default: cout<<"Error"; break;
            }
            strcat(temp3,temp);
            strcat(temp3,temp2);
            paranthesise(temp3);
            s1.push(temp3);
        }
    }
    strcpy(temp2,s1.pop());
    cout<<"\nInfix:";
    puts(temp2); 
    return 0;
}

我發現的問題:

arr[20][20]={NULL};

是錯的。 這將NULL分配給arr[20][20] ,它不是數組的有效元素。 您正在設置不應該設置的內存值。 arr有效元素是arr[0][0] - arr[19][19]

這本身就足以讓程序表現出未定義的行為。

我會將構造函數更改為:

StringStack() : arr{}, top(-1) {}

當你使用

char temp[1];

它可以保存的唯一有效字符串是空字符串。 由於您打算使用它來保存一個由一個字符組成的字符串,因此您需要使用:

char temp[2] = ""; // Doesn't have to be 2 but it has to be 
                   // greater than 1.

paranthesise ,你有:

for(int i=l; i>=0; i++)

那需要是:

for(int i=l; i>=0; i--)

否則,您會繼續修改數組,而不會滿足結束循環的條件。 不僅如此,您最終還會修改超出有效限制的數組。

暫無
暫無

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

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