liveBook · Manning

Strndup

As explained in Modern C, Third Edition

strndup is a C23 library function that allocates storage and copies at most a specified number of characters from a string.

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

How Modern C, Third Edition covers it

How deep it goes
Explains input bounds, termination, allocation failure, and an implementation sketch, stopping short of deeper allocation mechanics.
Examples
Demonstrates copying a three-character prefix and inspecting a reference implementation based on memchr and memcpy.
What it assumes
Assumes familiarity with C strings, zero termination, function declarations, and dynamically allocated storage.
What you can do after
Apply it via the C23 library to create bounded allocated strings and handle allocation failure.
How it connects
Connects strndup with strdup, malloc, memchr, memcpy, and null-terminated C strings.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.