strndup.c 462 Bytes
Newer Older
1 2 3 4
/* strndup.c
 *
 */

Niels Möller's avatar
Niels Möller committed
5
/* Written by Niels Möller <nisse@lysator.liu.se>
6 7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * This file is hereby placed in the public domain.
 */

#include <stdlib.h>
#include <string.h>

char *
strndup (const char *s, size_t size)
{
  char *r;
  char *end = memchr(s, 0, size);
  
  if (end)
20 21
    /* strlen, i.e., excluding the terminating NUL. */
    size = end - s;
22
  
23
  r = malloc(size+1);
24

25
  if (r)
26
    {
27 28
      memcpy(r, s, size);
      r[size] = '\0';
29 30 31
    }
  return r;
}