4 ms·
You can use strncpy if you are careful to do it right (e.g. if you know the end of the destination buffer is null-terminated, specify the length one less than t
by zzo38computer 4y ago
You can use strncpy if you are careful to do it right (e.g. if you know the end of the destination buffer is null-terminated, specify the length one less than the destination buffer size). Sometimes memcpy is better, though. You can use both in one program.
- masklinn 4y ago> You can use strncpy if you are careful to do it right That’s like saying if you’re careful to do it right you can use a Bowie knife as a screwdriver. Technically correct but practically will end in tears. If you’re not working with fixed-size strings (which few are these days) just copy over strscpy, or strlcpy, 5 lines won’t kill you.
- kevin_thibedeau 4y agoYou're still stuck with the zero pad performance hit when the destination is significantly larger than the source.
- noselasd 4y agoBut you don't want to use strncpy, especially not inside the kernel - since it may waste a lot of useless cpu. char big_enough[512]; strncpy(big_enough, sizeof 512, small_string]; strncpy now fills the rest of big_enough with nuls, a lot of waste if small_string is 4 characters long.
- formerly_proven 4y agoThe express purpose of strncpy is to handle fixed-length strings in classic unix (file) structures (e.g. tar), I'm not convinced it's correct to use in basically any other situation.