Hacker News new | past | comments | ask | show | jobs | submit login

I'm glad you posted the article on strcpy; I did not know about this behavior of strncpy and am a little surprised I never ran into it before.

That being said; it is a safer alternative to strcpy, but it seems like it isn't the safest alternative to strcpy.




strncpy, when used as designed, can leave the target array without a terminating null character. Using that array later with any string function causes undefined behavior.

strcpy, when used as designed, always leaves the target array properly null-terminated. Using it properly is a bit more difficult; you have to make sure the target array is big enough to hold the source string.

This sequence:

    target[0] = '\0';
    strncat(target, source, sizeof target);
does what most people probably assume strncpy should do (assuming target is defined as an array rather than as a pointer).


What about strcpy_s ??


strcpy_s is not universally available.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: