[英]Seg Fault at return statement in function
我的程序應該將提示從中綴轉換為后綴。 到目前為止,通過調試器和其他各種方法,我找到了我的段錯誤的確切點,但不明白為什么。
這是我的代碼:
這是itop.h:
using namespace std;
#include <cstdlib>
#include <iostream>
class sNode{
public:
char data;
sNode *next;
};
class stack{
public:
sNode *head;
void push (char);
sNode pop();
int rank(char);
stack()
{
cout << "Initiliazing stack." << endl;
}
};
這是我的itop.cpp文件:
#include "itop.h"
void stack::push (char a)
{
// cout << "Pushing " << a << endl;
sNode *sn;
sn = new sNode;
sn->data = a;
sn->next = head;
head = sn;
}
sNode stack::pop()
{
// cout << "Popping stack." << endl;
sNode *sn;
sn = head;
head = head->next;
return *sn;
}
int stack::rank(char x)
{
int num = 0;
// cout << "Checking rank." << endl;
if(x == '\0')
{
num = 1;
// cout << "Checking for null" << endl;
return num;
}
else if(x == '+' || x == '-')
{
num = 2;
// cout << "Checking if + or -" << endl;
return num;
// cout << "After return." << endl;
}
else if(x == '*' || x == '/')
{
num = 3;
// cout << "Checking for * or /" << endl;
return num;
}
else
cout << "Error! Input not valid!" << endl;
}
這是main.cpp:
using namespace std;
#include <iostream>
#include <cstdlib>
#include <cstring>
#include "itop.h"
int main()
{
char *temp1; //Instantiating variables.
char *temp2;
temp1 = new char[20];
temp2 = new char [20];
stack s;
do //Checking commands.
{
cout << "infix_to_postfix> ";
cin >> temp1;
if(strcmp(temp1, "quit") == 0)
{
return 0;
}
if(strcmp(temp1, "convert") != 0)
{
cout << "Error! Invalid command." << endl;
}
cin >> temp2;
if(strcmp(temp1, "convert") == 0)
{
for(int i=0; i<sizeof(temp2); i++)
{
if(isdigit(temp2[i]))
{
cout << atoi(&temp2[i]);
}
else if(s.rank(temp2[i]) < s.rank(s.head->data))
{
sNode temp = s.pop();
cout << temp.data;
}
else
{
s.push(temp2[i]);
}
}
}
else
{
cout << "Error! Command not supported." << endl;
}
}while(strcmp(temp1, "quit") != 0);
return 0;
}
該函數被調用
else if(s.rank(temp2[i]) < s.rank(s.head->data))
問題出在這里:
else if(x == '+' || x == '-')
{
num = 2;
// cout << "Checking if + or -" << endl;
return num;
// cout << "After return." << endl;
}
特別是在返回num之前,我得到“Segmentation fault(core dumped)”錯誤消息。 我使用了gdb,我所知道的就是在“檢查是否+或 - ”之后我看到“$ 1 = 2”。 我不太清楚這意味着什么,但這是我想要回歸的。
謝謝您的幫助。
您的代碼中存在許多錯誤。 您的堆棧實現是錯誤的。 push()
例如只反復設置head
。 這導致您的堆棧類只能容納一個元素。 next
永遠不會設置為任何東西,所以它包含隨機垃圾。 再往下,你有這個:
for(int i=0; i<sizeof(temp2); i++)
sizeof(temp2)
不會給出temp2
指向的字符串的字符數。 它為您提供指針temp2
本身的大小。 此外,您最終從空堆棧中讀取s.head
,這將是指向隨機垃圾的指針。 那時候,所有的賭注當然都沒有了。 除了崩潰和燒傷之外別無其他。
修復1:編寫適當的構造函數。
stack()
{
head=NULL;
cout << "Initiliazing stack." << endl;
}
修復2:編寫一個額外的方法來檢查堆棧是否為空。
int stack::empty()
{
if(head == NULL)
return true;
else
return false;
}
修復3:在使用堆棧數據之前檢查堆棧是否為空。
else if(!s.empty() && s.rank(temp2[i]) < s.rank(s.head->data))
{
...
}
修復4:修復其余的代碼邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.