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

The only thing more dangerous than strcpy is strlcpy or strncpy. I can't tell you how many times I've seen:

strncpy(dst, src, sizeof(src));

And the developer thinks that the code is safer because he's using the "safer" function.




I hope you meant strlen in place of sizeof


Most people use sizeof when they are copying between static buffers on the stack. Strlen would be just as bad of an idea in this example because they're using the src buffer as the limit on the copy rather than the dst buffer which is still vulnerable to overflow. Should be:

strncpy(dst, src, sizeof(dst)-1);

Edit: bad code


or sizeof(dst), and not forgetting dst[sizeof(dst)-1]='\0';


That's why strlcpy is safer than strncpy, it makes sure that the destination string will always be zero-terminated.


I can't see how that would make it more dangerous. It's still not foolproof, but at least it isn't completely braindead like strcpy().




Join us for AI Startup School this June 16-17 in San Francisco!

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

Search: