strdup - Duplicate String

Format

#include <string.h>
char *strdup(const char *string);

Note:
The strdup function is available for C++ programs. It is available for C only when the program defines the __cplusplus__strings__ macro.

Language Level: XPG4, Extension

Threadsafe: Yes.

Description

strdup reserves storage space for a copy of string by calling malloc. The string argument to this function is expected to contain a null character (\0) marking the end of the string. Remember to free the storage reserved with the call to strdup.

Return Value

strdup returns a pointer to the storage space containing the copied string. If it cannot reserve storage strdup returns NULL.

Example that uses strdup()

This example uses strdup to duplicate a string and print the copy.

#include <stdio.h>
#include <string.h>
int main(void)
{
   char *string = "this is a copy";
   char *newstr;
   /* Make newstr point to a duplicate of string                              */
   if ((newstr = strdup(string)) != NULL)
      printf("The new string is: %s\n", newstr);
   return 0;
}

The output should be:

      The new string is: this is a copy

Related Information:



[ Top of Page | Previous Page | Next Page | Contents | Index ]