c - 使用 scanf 时程序立即终止并出现段错误

标签 c pointers segmentation-fault scanf

当我使用 gets()fgets() 而不是 scanf() 时,程序会完全执行但会打印段错误(核心倾倒)到底!我不明白为什么我在这两种情况下都会遇到段错误。下面是使用堆栈将中缀转换为后缀 exp 的代码。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct stack{
    int top;
    int capacity;
    int *array;
}stack;

stack* createstack(char *);
void push(stack* ,int );
int isempty(stack *);
int pop(stack *st);
int peek(stack *st);
int precedence(char c);

int main(){
char exp[100];
char post[100];
int k=-1;
stack *st;
int i=0,p=0;
printf("enter string expression: ");
//gets(exp); 
//fgets(exp, sizeof(exp), stdin);
scanf("%s",exp);
printf("Infix expression : %s",exp);
st=createstack(exp);

for(i=0;i<strlen(exp);i++){
    if( (exp[i]>='a' && exp[i]<='z') || (exp[i]>='A' && exp[i]<='Z'))
        post[++k]=exp[i];
    else if(exp[i]=='(')
        push(st,exp[i]);
    else if(exp[i]==')'){
        while(!isempty(st) && peek(st)!='(')
            post[++k]=pop(st);
        pop(st);
    }
    else{
        while(precedence(exp[i]) < precedence(peek(st)))
            post[++k]=pop(st);
        push(st,exp[i]);
    }
}
while(!isempty(st))
    post[++k]=pop(st);

//post[++k]='\0';
printf("Postfix expression :\n%s\n",post);
return 0;

}

stack* createstack(char *exp){
stack* st;
st->top=-1;
st->capacity=strlen(exp);
st->array=(int*)malloc(st->capacity * sizeof(int));
printf("Stack created successfully\n");
return st;
}

void push(stack* st,int val){
st->array[++st->top]=val;
}

int isempty(stack *st){
return st->top==-1;
}

int pop(stack *st){
return st->array[st->top--];
}

int peek(stack *st){
return st->array[st->top];
}

int precedence(char c){
switch(c){
    case '(':
        return 0;
        break;
    case '+':
        return 1;
        break;
    case '-':
        return 1;
        break;
    case '*':
        return 2;
        break;
    case '/':
        return 2;
        break;

    case '^':
        return 3;
        break;
    }
}       

最佳答案

在你的代码中,

stack* st;
st->top=-1;

您正在使用 st 未初始化,这又会调用 undefined behaviour .

使用前需要给st分配内存。

尝试类似的东西

stack* st = malloc(sizeof*st);  //also, check for malloc success

也就是说,

  1. see why not to cast malloc()C 中的 family 的返回值。

  2. main() 的推荐签名是int main(void)

关于c - 使用 scanf 时程序立即终止并出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30931798/

相关文章:

c - 函数中的本地字符数组保留先前调用的值

c - 访问地址内保存的地址

c++ - 使用 -O3 使用 g++ 编译时 C++ 程序中的段错误

C:如何访问 Net-SNMP GET 返回的值

使用 extern struct 时 XC8 中的声明冲突

c - 在C语言游戏中使用鼠标控制

c - 热衷于将 TXT 文件转换为结构数组 - 段错误?

c - 该代码将生成多少个进程?

c - C语言中,如何用指针计算一个字符串中有多少个元音字母?

c++ - 为什么将 'char' 分配给 'char' 会产生段错误? C++