title: Unsafe C functions and the replacement
body: <p>Please correct me if I'm wrong, I research in the site but can't find any consolidated post for this problem. There are many unsafe functions in C that can lead to buffer overflow and they have the safe functions to replace them. I have a few:</p>
  
  <ul>
  <li><code>gets()</code> === replace by === <code>fgets()</code></li>
  <li><code>sprintf()</code> === replace by === ?</li>
  <li><code>strcat()</code> === replace by === ?</li>
  <li><code>strcpy()</code> === replace by === <code>strncpy()</code></li>
  <li><code>vsprintf()</code> === replace by === <code>vsnprintf()</code></li>
  </ul>
  
  <p>Also, I stuck with the unsafe byte copy and unsafe byte input code below. How can I fix the problems?
  Why does this code have vulnerability? </p>
  
  <pre><code>int copy_buf (char *to, int pos, char *from, int len)
  {
      int i;
      for (i=0;i&lt;len;&lt;i++){
           to[pos] = from [i];
           pos++;
      }
      return pos
  }
  </code></pre>
  
  <p>For the byte input, is the <code>fread()</code> unsafe function? Why does the buffer overflow happen here? </p>
  
  <pre><code>short read_chunk(FILE fil, char *to)
  {
      short len;
      fread(&amp;len, 2, 1, fil);
      fread(to, 1, len, fil);
      return len;
  }
  </code></pre>