blob: 1db7069b80c4b3b8729f302d94ce02c03182167e (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
/* -*- mode: c; c-file-style: "openbsd" -*- */
#include <stdlib.h>
#include <string.h>
#include "compat.h"
/*
* Similar to `strdup()` but copies at most n bytes.
*/
char *
strndup(const char *string, size_t maxlen)
{
char *result;
/* We may use `strnlen()` but it may be unavailable. */
const char *end = memchr(string, '\0', maxlen);
size_t len = end ? (size_t)(end - string) : maxlen;
result = malloc(len + 1);
if (!result) return 0;
memcpy(result, string, len);
result[len] = '\0';
return result;
}
|