2 ms·
Here is one way to handle strncpy() that works in a lot of cases: strncpy(newBuf, oldBuf, size); newBuf[size-1] = 0; That way you always end up with a null. I
by ktRolster 9y ago
Here is one way to handle strncpy() that works in a lot of cases:
strncpy(newBuf, oldBuf, size);
newBuf[size-1] = 0;
That way you always end up with a null. It adds the null even when you don't need it, but that's more efficient than adding an 'if' statement.
- a_t48 9y agoThat still has poor behavior if newBuf is much larger than oldBuf.
- monochromatic 9y agoIt leaves the small problem and fixes the big problem.
- ktRolster 9y agoWhat poor behavior? Presumably oldBuf is null-terminated, so there will be no buffer overflow (if your strings aren't null-terminated, you have other problems)
- tarpherder 9y agoWhat if size becomes zero?