Returns a pointer to a null-terminated byte string, which contains copies of at most size
bytes from the string pointed to by src
. The space for the new string is obtained as if malloc was called. If the null terminator is not encountered in the first size
bytes, it is appended to the duplicated string.
The returned pointer must be passed to free to avoid a memory leak.
If an error occurs, a null pointer is returned and errno might be set.
[edit] Parameters src - pointer to the null-terminated byte string to duplicate size - max number of bytes to copy fromsrc
[edit] Return value
A pointer to the newly allocated string, or a null pointer if an error occurred.
[edit] NotesThe function is identical to the POSIX strndup except that it is allowed, but not required to set errno on error.
[edit] Example#include <string.h> #include <stdio.h> #include <stdlib.h> int main(void) { const size_t n = 3; const char *src = "Replica"; char *dup = strndup(src, n); printf("strndup(\"%s\", %lu) == \"%s\"\n", src, n, dup); free(dup); src = "Hi"; dup = strndup(src, n); printf("strndup(\"%s\", %lu) == \"%s\"\n", src, n, dup); free(dup); const char arr[] = {'A','B','C','D'}; // NB: no trailing '\0' dup = strndup(arr, n); printf("strndup({'A','B','C','D'}, %lu) == \"%s\"\n", n, dup); free(dup); }
Output:
strndup("Replica", 3) == "Rep" strndup("Hi", 3) == "Hi" strndup({'A','B','C','D'}, 3) == "ABC"[edit] See also
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4