title: Is this a good substr for C?
body: <p>See also <a href="https://stackoverflow.com/questions/874161/c-tokenizer-and-it-returns-empty-too-when-fields-are-missing-yay">C Tokenizer</a></p>
  
  <hr>
  
  <p>Here is a quick substr() for C that I wrote (yes, the variable initializations needs to be moved to start of the function etc, but you get the idea)</p>
  
  <p>I have seen many "smart" implementations of substr() that are simple one liner calls strncpy()!</p>
  
  <p>They are all wrong (strncpy does not guarantee null termination and thus the call might NOT produce a correct substring!)</p>
  
  <p>Here is something maybe better?</p>
  
  <p>Bring out the bugs!</p>
  
  <pre><code>char* substr(const char* text, int nStartingPos, int nRun)
  {
      char* emptyString = strdup(""); /* C'mon! This cannot fail */
  
      if(text == NULL) return emptyString;
  
      int textLen = strlen(text);
  
      --nStartingPos;
  
      if((nStartingPos &lt; 0) || (nRun &lt;= 0) || (textLen == 0) || (textLen &lt; nStartingPos)) return emptyString;
  
      char* returnString = (char *)calloc((1 + nRun), sizeof(char));
  
      if(returnString == NULL) return emptyString;
  
      strncat(returnString, (nStartingPos + text), nRun);
  
      /* We do not need emptyString anymore from this point onwards */
  
      free(emptyString);
      emptyString = NULL;
  
      return returnString;
  }
  
  
  int main()
  {
      const char *text = "-2--4--6-7-8-9-10-11-";
  
      char *p = substr(text, -1, 2);
      printf("[*]'%s' (\")\n",  ((p == NULL) ? "&lt;NULL&gt;" : p));
      free(p);
  
      p = substr(text, 1, 2);
      printf("[*]'%s' (-2)\n", ((p == NULL) ? "&lt;NULL&gt;" : p));
      free(p);
  
      p = substr(text, 3, 2);
      printf("[*]'%s' (--)\n", ((p == NULL) ? "&lt;NULL&gt;" : p));
      free(p);
  
      p = substr(text, 16, 2);
      printf("[*]'%s' (10)\n", ((p == NULL) ? "&lt;NULL&gt;" : p));
      free(p);
  
      p = substr(text, 16, 20);
      printf("[*]'%s' (10-11-)\n", ((p == NULL) ? "&lt;NULL&gt;" : p));
      free(p);
  
      p = substr(text, 100, 2);
      printf("[*]'%s' (\")\n", ((p == NULL) ? "&lt;NULL&gt;" : p));
      free(p);
  
      p = substr(text, 1, 0);
      printf("[*]'%s' (\")\n", ((p == NULL) ? "&lt;NULL&gt;" : p));
      free(p);
  
      return 0;
  }
  </code></pre>
  
  <blockquote>
    <p>Output :</p>
  </blockquote>
  
  <pre><code>[*]'' (")
  [*]'-2' (-2)
  [*]'--' (--)
  [*]'10' (10)
  [*]'10-11-' (10-11-)
  [*]'' (")
  [*]'' (")
  </code></pre>