title: C: wrong allocation of the pointer
body: <p>I have a char-array and I want to remove whitespace just before or after or both, the word (or phrase) and not in the middle.</p>
  
  <p>For example:</p>
  
  <p>"hello" --> "hello"</p>
  
  <p>" hello" --> "hello"</p>
  
  <p>" hello " --> "hello"</p>
  
  <p>" " --> ""</p>
  
  <p>This is my code:</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  int main(void) 
  {
      char s[] = " prova ";
      char *t = NULL;
      if (s == NULL)
      {
          t = NULL;
      }
      else {
          int n = strlen(s);
          t = malloc(sizeof(char)* (n + 1));
          for (int i = 0; i &lt;= n; ++i)
          {
              t[i] = s[i];
          }
          int k = 0;
          if (s[0] == ' ')
          {
              ++k;
              t = realloc(t, sizeof(char)*n);
              for (int i = 0; i &lt;= n - 1; ++i)
              {
                  t[i] = s[i + 1];
              }
          }
  
          if (s[n - 1] == ' ')
          {
              if (k == 1)
              {
                  int j = 0;
                  t = realloc(t, sizeof(char)*(n - 1));
                  for (int i = 0; i &lt;= n - 2; ++i)
                  {
                      t[i] = t[i];
                      j = i;
                  }
                  t[j] = 0;
              }
              else
              {
                  int j = 0;
                  t = realloc(t, sizeof(char)*n);
                  for (int i = 0; i &lt;= n - 1; ++i)
                  {
                      t[i] = t[i];
                      j = i;
  
                  }
                  t[j] = 0;
              }
          }
      }
      return t;
  }
  </code></pre>
  
  <p>The debugging does not give me error or other things, but I know there is a problem with memory and heap and I don't know how to remove it.</p>
  
  <p>I looked for other questions similar to mine on this platform and they exist, but none of the answers solved my problem.</p>
  
  <p>Please give me some advice, thank you</p>