title: Remove Trailing Spaces in C
body: <p>I'm trying to remove trailing spaces however I keep getting a segmentation fault. Not too sure where I am accessing memory out of bounds but this is my code. Leading spaces works fine.</p>
  
  <p>String is the input for the function.</p>
  
  <pre><code>//remove leading spaces
  char* final = string;
  while(isspace((unsigned char)final[0]))
          final++;
  
   //removing trailing spaces
  //getting segmentation fault here
      int length = strlen(final);
      while(length &gt; 0 &amp;&amp; isspace((unsigned char)final[length-1]))
              length--;
      final[length-1] = '\0';
  </code></pre>
  
  <p>The string I tested was </p>
  
  <pre><code>char* word = "  1 2 Hello    ";
  printf("%s\n", removeSpaces(word));
  </code></pre>
  
  <p>When I comment out the trailing spaces, it works perfectly. I don't why the code is failing at the trailing spaces. I would really appreciate the help.</p>