0

When I use gets() or fgets() instead of scanf(), the program does execute completely but prints segmentation fault(core dumped) in the end! I don't understand why am I getting segfault in both the cases. Here is the code for converting an infix to postfix exp using stacks.

#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;
    }
}       
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
minzey
  • 116
  • 2
  • 11
  • 1
    minor note: please try to give a minimum code example. in your case, you could probably reduce it to 5 to 10 lines. this saves time of people who read your answer, and makes the question more general, which means it can help more people with similar problems. it will also maybe help you to find the error yourself. – hoijui Jun 19 '15 at 06:59

1 Answers1

3

In your code,

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

you're using st uninitialized which in turn invokes undefined behaviour.

You need to allocate memory to st before using it.

Try something like

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

That said,

  1. Please see why not to cast the return value of malloc() and family in C.

  2. The recommended signature of main() is int main(void).

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261