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

There is one, and it exist inside the gnu libc.

strndup performs identical to strncpy except that it always terminates the destination string. (https://www.gnu.org/software/libc/manual/html_node/Copying-a...)



You remember the Holy Grail scene from Indiana Jones? The problem is not the absence of the grail, somewhere on the shelf. The problem is all the others and the fact that if you pick the wrong one, your program desiccates, crumbles to dust, and is blown away by a conveniently dramatic wind.

A grail shelf that wasn't intended as a booby trap would contain one cup, the right one.


But this is the great advantage of C! It's one Holy Grail for every platform! Choice is wonderful!

/sarcasm


strndup is not a replacement for strncpy, it allocates memory, whereas strncpy takes an existing buffer. In-place memory usage is very important for preparing anything of a fixed size (structs) to be written out to disk or the network.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

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

Search: