CKTIS / C
strncat — append with a source-byte limit
strncat appends at most n source bytes to a string and adds '\0'. The parameter n is not the destination buffer capacity.
Version: C23; repository compiler flag, production runtime not attested
Syntax
#include <string.h>
char *strncat(char * restrict s1, const char * restrict s2, size_t n);strncat from <string.h> appends at most n bytes from s2 to s1, stopping earlier at '\0'. It overwrites the existing terminator and adds a new one. It returns s1, not a length or truncation status.
s1 must point to a writable, null-terminated string. The source must provide n readable bytes or an earlier terminator. Insufficient space or overlapping regions during copying causes undefined behavior.
n limits source data, not the result size. Do not use strlen(s1) + n + 1 as an unchecked capacity test: unsigned arithmetic can wrap and produce a value that is too small. If capacity is the destination buffer capacity in bytes and strlen(s1) < capacity, then n <= capacity - strlen(s1) - 1 guarantees room for up to n appended bytes and the new terminator. For a correctly terminated array dst, compute remaining space as sizeof dst - strlen(dst) - 1; do not use this formula with sizeof a pointer. With n == 0, the string remains unchanged, but the pointers must still be valid.
Examples
#include <stdio.h>
#include <string.h>
int main(void)
{
char dst[10] = "Hi ";
const char src[] = "there!";
size_t room = sizeof dst - strlen(dst) - 1;
strncat(dst, src, room);
puts(dst);
return 0;
}
Result
Hi there!
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.