strndup allocates storage and copies at most n characters from a character buffer, returning a newly allocated, null-terminated string. Unlike strdup, it does not require the input to be null-terminated beyond the first n bytes. section 13.1 section 6.1.5
Copy a bounded prefix
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char const input[] = "abcdef"; char *copy = strndup(input, 3); if (copy) { printf("%s\n", copy); /* abc */ free(copy); } } section 13.1
The function examines at most the first n bytes. If it finds a zero byte, the copy includes that terminator; otherwise, it copies n characters and writes a zero byte after them. Consequently, a successful result is always a string. section 13.1
TAKEAWAY
- Prefer strndup when a bound for the input string is available. section 13.1
- Check the returned pointer before using the copy: failed allocation produces a null pointer. section 13.1
- The input must either contain a zero byte within the first n bytes or provide at least n accessible bytes. section 13.1
