title: Why do I get segmentation error when calling a parsing function in C
body: <p>I have been trying to understand how this custom function below works to parse lines from argv but I keep getting segmentation errors.
  I have been trying to debug it for hours but I cannot find the bug that is eating into &quot;restricted memory&quot;
  The function takes a string literal and a delimiter string (not character).</p>
  <p>When I use <code>valgrind</code> to audit the function, it reports a SIGSEGV error when calling strtok.</p>
  <p>I understand strtok cannot work directly with string literals because it can cause undefined behaviour. So I decided to copy the <code>str</code> to a local variable first.</p>
  <p>Yes, I tried using an array as copy too, but it still throws the segmentation error.</p>
  <p>What I really don't understand is why does strtok not getting enough memory?</p>
  <pre><code>char **splitstring(char *str, const char *delim)
  {
      int i, wn;
      char **array;
      char *token;
      char *copy;
  
      copy = malloc(strlen(str) + 1);
      if (copy == NULL)
      {
          perror(&quot;hsh&quot;);
          return (NULL);
      }
      i = 0;
      while (str[i])
      {
          copy[i] = str[i];
          i++;
      }
      copy[i] = '\0';
  
      token = strtok(copy, delim);
      array = malloc((sizeof(char *) * 2));
      array[0] = strdup(token);
  
      i = 1;
      wn = 3;
      while (token)
      {
          token = strtok(NULL, delim);
          array = realloc(array, (sizeof(char *) * (wn - 1)), (sizeof(char *) * wn));
          array[i] = strdup(token);
          i++;
          wn++;
      }
      free(copy);
      return (array);
  }
   
  </code></pre>