Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I personally am of the mindset that if the code can be proven to be valid—and done so quickly—it is perfectly acceptable. That is, if the code is simple and thus obviously correct, then it is fine.</p> <p>However, your assumption seems to be that while your function is executing, no other thread will modify the string pointed to by <code>s1</code>. What happens if this function is interrupted after successful memory allocation (and thus the call to <code>strlen</code>), the string grows, and <strong>bam</strong> you have a buffer overflow condition since <code>strcpy</code> copies to the NULL byte.</p> <p>The following might be better:</p> <pre><code>char * strdup(const char *s1) { int s1_len = strlen(s1); char *s2 = malloc(s1_len+1); if(s2 == NULL) { return NULL; } strncpy(s2, s1, s1_len); return s2; } </code></pre> <p>Now, the string can grow through no fault of your own and you're safe. The result will not be a dup, but it won't be any crazy overflows, either.</p> <p>The probability of the code you provided <em>actually</em> being a bug is pretty low (pretty close to non-existent, if not non-existent, if you are working in an environment that has no support for threading whatsoever). It's just something to think about.</p> <p><strong>ETA</strong>: Here is a slightly better implementation:</p> <pre><code>char * strdup(const char *s1, int *retnum) { int s1_len = strlen(s1); char *s2 = malloc(s1_len+1); if(s2 == NULL) { return NULL; } strncpy(s2, s1, s1_len); retnum = s1_len; return s2; } </code></pre> <p>There the number of characters is being returned. You can also:</p> <pre><code>char * strdup(const char *s1) { int s1_len = strlen(s1); char *s2 = malloc(s1_len+1); if(s2 == NULL) { return NULL; } strncpy(s2, s1, s1_len); s2[s1_len+1] = '\0'; return s2; } </code></pre> <p>Which will terminate it with a <code>NUL</code> byte. Either way is better than the one that I quickly put together originally.</p>
    singulars
    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.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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