3 ms·
using strlen(src) is also an amateur mistake, because the whole point of doing that (stncpy family, ensuring dst ends with null) is that dst might not be large
by zeusk 8y ago
using strlen(src) is also an amateur mistake, because the whole point of doing that (stncpy family, ensuring dst ends with null) is that dst might not be large enough to fit string from src.
It has to be the size of dst, which can only be known at the site of allocation in C (except for a non-clean way of looking at heap metadata).
- jonathankoren 8y agoThere’s no reason to believe from these two lines that the memory is insufficiently allocated. It’s just two lines. The point wasn’t to share a safe string copy routine, the point of the post was to illustrate a single mistake.
- zeusk 8y agoI'm not assuming that, but then you can't assume the memory is sufficient either. If the string is from network or user, then you can never assume the buffer to be of sufficient size (which they definitely do, because they aren't tracking how much of src was copied into allocated dst).
- ploxiln 8y agoEach line, individually, is total nonsense. It never makes sense to use strlen() for an argument to strncpy(). Only the size of the destination buffer makes sense for strncpy() (usually sizeof(dst)). For other cases you would probably use memcpy().