CKTIS / C
strncpy — copying with zero padding
strncpy writes n bytes, padding short input with zeros. It does not guarantee a '\0'-terminated result.
Version: C23; repository compiler flag, production runtime not attested
Syntax
#include <string.h>
char *strncpy(char * restrict s1, const char * restrict s2, size_t n);strncpy, declared in <string.h>, copies from s2 to s1 and returns s1. If it encounters '\0' before the limit n, it pads the result with zeros to exactly n bytes.
If the first n source bytes contain no '\0', the result lacks a terminator. n is not an automatic capacity check: the destination must hold n bytes, and the source must be readable through its first '\0' or for n bytes. Overlapping regions cause undefined behavior.
Do not pass an unterminated result to unbounded %s. The example demonstrates padding and truncation; %.*s bounds the read from truncated.
Examples
#include <stdio.h>
#include <string.h>
int main(void)
{
char padded[5];
char truncated[3];
strncpy(padded, "Hi", sizeof padded);
strncpy(truncated, "Hello", sizeof truncated);
printf("padded: %s; zero padding: %d %d %d\n",
padded, padded[2] == '\0', padded[3] == '\0',
padded[4] == '\0');
printf("truncated: %.*s\n", (int)sizeof truncated, truncated);
return 0;
}
Result
padded: Hi; zero padding: 1 1 1 truncated: Hel
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.