Embedded Artistry libc
C Standard Library Support for Bare-metal Systems
strndup.c File Reference
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
Include dependency graph for strndup.c:

Go to the source code of this file.

Functions

char * strndup (const char *str, size_t n)
 Duplicate n bytes of the passed in string str. More...
 

Function Documentation

◆ strndup()

char* strndup ( const char *  str,
size_t  n 
)

Duplicate n bytes of the passed in string str.

strndup is similar to

See also
strdup, but copies at most n bytes. If str is longer than n, only n bytes are copied, and a terminating null byte ('\0') is added.
Parameters
stra pointer to a string to duplicate
nmaximum number of bytes to copy
Returns
a pointer to the duplicated string on success. NULL if insufficient memory was available, with errno set to indicate cause of error.

Definition at line 41 of file strndup.c.

42 {
43  char* copy = NULL;
44 
45  if(str && n)
46  {
47  size_t len;
48 
49  for(len = 0; len < n && str[len]; len++)
50  {
51  }
52 
53  if((copy = malloc(len + 1)) == NULL)
54  {
55  return (NULL);
56  }
57 
58  memcpy(copy, str, len);
59  copy[len] = '\0';
60  }
61 
62  return copy;
63 }
#define NULL
Definition: stddef.h:15
void * malloc(size_t size)
Allocates size bytes of uninitialized storage.
void * memcpy(void *__restrict dest, const void *__restrict src, size_t n)
Copies n characters from the object pointed to by src to the object pointed to by dest.

References malloc(), memcpy(), and NULL.