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

Go to the source code of this file.

Functions

char * strdup (const char *str)
 Duplicate the passed in string str. More...
 

Function Documentation

◆ strdup()

char* strdup ( const char *  str)

Duplicate the passed in string str.

Returns a pointer to a new string which is a duplicate of the string str. Memory for the new string is obtained with malloc(3), and can be freed with free(3).

Parameters
stra pointer to a string to duplicate
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 42 of file strdup.c.

43 {
44  char* copy = NULL;
45 
46  if(str)
47  {
48  size_t len = strlen(str) + 1;
49 
50  if((copy = malloc(len)) == NULL)
51  {
52  return (NULL);
53  }
54 
55  memcpy(copy, str, len);
56  }
57 
58  return (copy);
59 }
size_t strlen(const char *str)
Returns the length of the given null-terminated byte string.
Definition: strlen.c:77
#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(), NULL, and strlen().