6 ms·
Always use strndup(). Never trust your input.
by scdlbx 16y ago
Always use strndup(). Never trust your input.
- apenwarr 16y agoIf you're trying to strdup() something you're not even sure is null-terminated, you're already doomed.
- scott_s 16y agoThe parent said to use strndup(), which takes a max value of characters to copy.
- CamperBob 16y agoAnd adds a \0 after the characters copied, which means you have to remember to do the sizeof(dest)-1 thing to avoid an overwrite. The people who designed the C string functions should have been made to pee in a cup before they were allowed into the building. So much trouble could have been avoided if they had only been consistent about using memory block sizes as parameters rather than "string" (sic) lengths.
- scott_s 16y agoWhich is annoying, yes, but using strndup() negates apenwarr's point.
- __david__ 16y agoWhat are you talking about? There is no sizeof(dest) with strndup()--it's newly allocated memory sized appropriately so there's no chance of an overwrite.
- tptacek 16y agoWhile we're on the subject, what is the point of strndup()? Keeping people from running you out of memory with big long strings? They'll just find other ways to do the same thing (by repeatedly feeding you strings of threshold length).
- CamperBob 16y ago(Actually it was strncpy's wacky behavior I was thinking of. I don't think I've ever used strndup().)