[英]Exited segmentation fault in c (infix to postfix)
我編寫了一個程序,將表達式從算術中綴表示法轉換為后綴。 這部分程序沒有問題。 但是,如果 char 在 7 后的最大 7 時,它的唯一轉換它的節目退出,分段錯誤。
可能是行號有錯誤。 108 或 97。
並請解釋鋤頭 malloc 的工作。 我使用 malloc 編寫了 2-3 個程序,但每個程序都顯示分段錯誤。
這是代碼:
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
struct stack
{
char *arr;
int top;
int size;
};
int isEmpty(struct stack *sp)
{
if(sp->top == -1 )
{
return 1;
}
else
{
return 0;
}
}
void push(struct stack *sp, char exp)
{
sp->top++;
sp->arr[sp->top] = exp;
}
char pop(struct stack *sp)
{
if(isEmpty(sp))
{
printf("stack underflow\n");
return -1;
}
else
{
char val = sp->arr[sp->top];
sp->top--;
return val;
}
}
int operator(char ch)
{
if(ch =='*' || ch =='/' || ch =='+' || ch =='-')
{
return 1;
}
else{
return 0;
}
}
int stackTop(struct stack* sp){
return sp->arr[sp->top];
}
int precedence(char ch)
{
if(ch =='*' || ch =='/' )
{
return 3;
}
else if(ch =='+' || ch =='-' )
{
return 2;
}
else
{
return 0;
}
}
char* conversion(char *exp)
{
struct stack *sp = malloc(sizeof(struct stack));
sp->top = -1;
sp->size = 100;
sp->arr = (char*)malloc(sp->size*sizeof(char));
char *pref = (char*)malloc((strlen(exp)+1)*sizeof(char));
int i=0,j=0;
while(exp[i]!='\0')
{
if(!operator(exp[i]))
{
pref[j] = exp[i];
j++;
i++;
}
else
{
if(precedence(exp[i])> precedence(stackTop(sp)))
{
push(sp, exp[i]);
i++;
}
else{
pref[j] = pop(sp);
j++;
}
}
}
while(!isEmpty(sp))
{
pref[j] = pop(sp);
j++;
}
pref[j] = '\0';
return pref;
}
int main(void)
{
char exp;
printf("Enter the expression:\n");
scanf("%s", &exp);
char *inf = &exp;
printf("Finally: %s", conversion(inf));
}
char exp;
printf("Enter the expression:\n");
scanf("%s", &exp);
char *inf = &exp;
不好。 exp
只有一個字符的空間,但您試圖在那里讀取多個字符,導致危險的超出范圍寫入。
您應該分配足夠的元素並指定要讀取的最大長度以避免緩沖區溢出。 最大長度應該是緩沖區大小減一以終止空字符。
char exp[102400]; /* allocate enough size */
printf("Enter the expression:\n");
scanf("%102399s", exp); /* remove & and specify the maximum length */
char *inf = exp; /* remove & */
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.