Note that there are some explanatory texts on larger screens.

plurals
  1. POC strcpy() - evil?
    primarykey
    data
    text
    <p>Some people seem to think that C's <code>strcpy()</code> function is bad or evil. While I admit that it's usually better to use <code>strncpy()</code> in order to avoid buffer overflows, the following (an implementation of the <code>strdup()</code> function for those not lucky enough to have it) safely uses <code>strcpy()</code> and should <em>never</em> overflow:</p> <pre><code>char *strdup(const char *s1) { char *s2 = malloc(strlen(s1)+1); if(s2 == NULL) { return NULL; } strcpy(s2, s1); return s2; } </code></pre> <p><code>*s2</code> is guaranteed to have enough space to store <code>*s1</code>, and using <code>strcpy()</code> saves us from having to store the <code>strlen()</code> result in another function to use later as the unnecessary (in this case) length parameter to <code>strncpy()</code>. Yet some people write this function with <code>strncpy()</code>, or even <code>memcpy()</code>, which both require a length parameter. I would like to know what people think about this. If you think <code>strcpy()</code> is safe in certain situations, say so. If you have a good reason not to use <code>strcpy()</code> in this situation, please give it - I'd like to know why it might be better to use <code>strncpy()</code> or <code>memcpy()</code> in situations like this. If you think <code>strcpy()</code> is okay, but not here, please explain.</p> <p>Basically, I just want to know why some people use <code>memcpy()</code> when others use <code>strcpy()</code> and still others use plain <code>strncpy()</code>. Is there any logic to preferring one over the three (disregarding the buffer checks of the first two)?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload