Name

strndup
- save a copy of a string

Library

libc.lib

Synopsis

  #include <string.h>
  char * strndup (const char *str, size_t n);

Detailed description

The strndup function allocates sufficient memory for a copy of the string str, does the copy of at most n characters, and returns a pointer to it. If str is longer than n, only n characters are copied and a terminating NULL is added. The pointer may subsequently be used as an argument to the function free.

If insufficient memory is available, NULL is returned and errno is set to ENOMEM.


Examples

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
    char* ptr;
    ptr = (char *)strndup("abcde",3);
    printf("Duplicated string %s\n",ptr);
    ptr = (char *)strndup("Hello Hi",5);
    printf("Duplicated string %s\n",ptr);
    free(ptr);
    return 0;   
}

         

Output

Duplicated string abc
Duplicated string Hello

         

Return value

The strdup() function returns a pointer to the duplicated string, or NULL if insufficient memory was available.

See also

free, malloc

Feedback

For additional information or queries on this page send feedback

© 2005-2007 Nokia

Top