0
votes

I have written a program which converts expressions from arithmetic infix notation to postfix. There is no issue with this part of the program. But its only convert if the char is max 7 after 7 its show exited, segmentation fault.

May be there's a error in line no. 108 or 97.

And please explain hoe malloc work. I had written 2-3 program by using malloc but every program once show segmentation error.

Here's code:

# 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));

  
}
1

1 Answers

1
votes
  char exp;
  printf("Enter the expression:\n");
  scanf("%s", &exp);

  char *inf = &exp;

is bad. exp has room for only one character, but you are trying to read multiple characters there, causing dangerous out-of-range write.

You should allocate enough elements and specify the maximum length to read to avoid buffer overrun. The maximum length should be the buffer size minus one for terminating null-character.

  char exp[102400]; /* allocate enough size */
  printf("Enter the expression:\n");
  scanf("%102399s", exp); /* remove & and specify the maximum length */

  char *inf = exp; /* remove & */