title: Why is this c++ code producing weird characters?
body: <p>I wanted to simplify algebraic expressions in c++. I started with something simple: removing brackets from a algebraic expression containing <code>+</code> and <code>-</code> operators. For example, <code>a-(b-c)</code> should be simplified to <code>a-b+c</code>. <a href="https://www.geeksforgeeks.org/remove-brackets-algebraic-string-containing-operators/" rel="nofollow noreferrer">This</a> link gives the answer to this question. Here is the source code:</p>
  <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt;
  #include &lt;string.h&gt;
  #include &lt;stack&gt;
  
  using namespace std; 
    
  // Function to simplify the string 
  char* simplify(string str) 
  { 
      int len = str.length(); 
    
      // resultant string of max length equal 
      // to length of input string 
      char* res = new char(len); 
      int index = 0, i = 0; 
    
      // create empty stack 
      stack&lt;int&gt; s; 
      s.push(0); 
    
      while (i &lt; len) { 
          if (str[i] == '+') { 
    
              // If top is 1, flip the operator 
              if (s.top() == 1) 
                  res[index++] = '-'; 
    
              // If top is 0, append the same operator 
              if (s.top() == 0) 
                  res[index++] = '+'; 
    
          } else if (str[i] == '-') { 
              if (s.top() == 1) 
                  res[index++] = '+'; 
              else if (s.top() == 0) 
                  res[index++] = '-'; 
          } else if (str[i] == '(' &amp;&amp; i &gt; 0) { 
              if (str[i - 1] == '-') { 
    
                  // x is opposite to the top of stack 
                  int x = (s.top() == 1) ? 0 : 1; 
                  s.push(x); 
              } 
    
              // push value equal to top of the stack 
              else if (str[i - 1] == '+') 
                  s.push(s.top()); 
          } 
    
          // If closing parentheses pop the stack once 
          else if (str[i] == ')') 
              s.pop(); 
    
          // copy the character to the result 
          else
              res[index++] = str[i]; 
          i++; 
      } 
      return res; 
  } 
  </code></pre>
  <p>I tested the function on <code>a-(b-c-(d+e))-f</code> and it gave the result <code>a-b+c+d+e-fÿï┌</code>. Why is it producing weird characters?</p>