4 ms·
pace @zeusk: I thought the point was that they didn't know if the dest is long enough to copy source, so they copy as much of it as they can. The reason for t
by projectramo 8y ago
pace @zeusk:
I thought the point was that they didn't know if the dest is long enough to copy source, so they copy as much of it as they can.
The reason for the '\0' is in the case that src is shorter than dest.
A more explicit way may be to strlen dest > src then just use lenght(src) otherwise use str(dest).
But this might actually be more efficient.
Edit: And in this case Spolsky doesn't apply because it seems the developer doesn't get to allocate the dest length.
- zeusk 8y agoWell... If dst is larger than src, the strcpy* family of functions will also copy over the null byte. If dst is shorter than src, and if strlen(src) is used as arg for strncpy then the function will overflow in dst and your null byte will also be outside dst buffer. In hardened environments you wouldn't trust strings to contain null byte if it comes from network or user and use strlcpy with known size of dst then append a null byte at end of dst anyway to ensure it is null terminated. Using strlen to compare buffer sizes is totally wrong and is the source for many bugs (hint, strlen doesn't actually return size of anything but the distance of the first null byte from the address you provide it).