Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I've got a better code snippet: your exact same code snippet but for a language which will short circuit based on the lvalue of the assignment expression.

Then t would never be able to overflow s (nor even eat its null terminator)



The size of the buffer pointed to by s may be larger than the current string it holds. It may also be uninitialized.


Or point to the wrong thing, or point to unmapped memory, or be const, or…there's a lot of things that can go wrong with this function.


The things I listed are things the function does right as written but could not do if it worked the way suggested above.

The things you listed are general concerns in C which are unrelated to both the correct implementation and the suggested changes.


That’s what strncpy() is for


Watch out: what strncpy does is usually not what you'd want it to do.


That's what strlcpy() is for.


Or strncpy, if you'd like to stay within the standard and your strings are small.


No, it's not. strcpy is fine to use if the destination buffer is larger than you need or uninitialized. That's idiomatic...




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

Search: