title: Infix to Postfix absurd value
body: <p>I have written a program below to convert Infix expression to Postfix expression.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  typedef struct Stack{
      int top;
      int capacity;
      char *array;
  }Stack;
  
  int isEmpty(Stack *s){
      return s-&gt;top == -1;
  }
  char pop(Stack *s){
      char c;
      if(isEmpty(s))
          return -1;
      c = s-&gt;array[s-&gt;top];
      s-&gt;array[s-&gt;top--] = '\0';
      return c;
  }
  
  void push(Stack *s,char c){
      s-&gt;array[++s-&gt;top] = c;
  }
  
  char peek(Stack *s){
      return s-&gt;array[s-&gt;top];
  }
  
  char *toString(char c){
      char *str = (char *)malloc(sizeof(char)*2);
      str[0] = c;
      str[1] = '\0';
      return str;
  }
  
  int hasGreaterPriority(char c1,char c2){
      if(c1 == '*' &amp;&amp; (c2 == '+' || c2 == '-'))
          return 1;
      else if(c1 == '/' &amp;&amp; (c2 == '+' || c2 == '-'))
          return 1;
      else
          return 0;
  }
  
  void infixtopostfix(char exp[]){
      int len = strlen(exp),i;
      char *out = (char *)malloc(sizeof(char));
      out[0] = '\0';
  
      Stack *stack = (Stack *)malloc(sizeof(Stack));
      stack-&gt;capacity = len;
      stack-&gt;top = -1;
      stack-&gt;array = malloc(sizeof(char)*len);
  
      for(i=0; i&lt;len; i++){
          if(exp[i] &gt;= 'a' &amp;&amp; exp[i] &lt;= 'z')
              strcat(out,toString(exp[i]));
          else if(exp[i] == ')'){
              while(peek(stack) != '(')
                  strcat(out,toString(pop(stack)));
              pop(stack);
          }
          else{
              if(isEmpty(stack) || exp[i] == '(')
                  push(stack,exp[i]);
              else if(hasGreaterPriority(peek(stack),exp[i])){
                  strcat(out,toString(pop(stack)));
                  push(stack,exp[i]);
              }
              else
                  push(stack,exp[i]);
         }
      }
      /* UNTIL HERE */
      while(!isEmpty(stack))
          strcat(out,toString(pop(stack)));
  
      printf("Postfix Expression: %s\n",out);
  }
  
  int main(void) {
      char exp[] = "a+b*(c/d-e)/(f+g*h)-i\0";
      printf("Infix Expression: %s\n",exp);
      infixtopostfix(exp);
      return 0;
  }
  </code></pre>
  
  <p>Problem is as follows:</p>
  
  <p>In infixtopostfix method, prior to while indicated by "UNTIL HERE" out variable value seems to be correct. I checked with the help of gdb. After 2 iterations of while loop also the value in out variable seems to be fine. In the last iteration i.e. while adding + into out,the value becomes as follows</p>
  
  <pre><code>abcd/e-fgh*+/i-*\377\377\377\377\025+
  </code></pre>
  
  <p>How did <code>\377\377\377\377\025+</code> get added to out variable? </p>
  
  <p>Expected value would be <code>abcd/e-fgh*+/i-*+</code></p>