2 ms·
I usually avoid strncpy() and strncat() altogether char buf[256]; size_t sz = strlen(str); if (sz < sizeof (buf)) { memcpy(buf, str, sz + 1); } else
by GuB-42 8y ago
I usually avoid strncpy() and strncat() altogether
char buf[256];
size_t sz = strlen(str);
if (sz < sizeof (buf)) {
memcpy(buf, str, sz + 1);
} else {
/* error processing */;
}
Truncation is not as bad as a buffer overflow. However, it is still not correct. You have to properly handle the case. And if truncating is the correct answer, make that explicit.
In practice, I almost never use fixed size buffers for strings unless I know the size at compile time.
Edit (for strcat):
char buf[256] = "blah";
size_t sz1 = strlen(buf);
size_t sz2 = strlen(str);
if (sz1 + sz2 < sizeof (buf)) {
memcpy(buf + sz1, str, sz2 + 1);
} else {
/* error processing */;
}