strdup -- Duplicate String

Format

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

Language Level: XPG4, Extension
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
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
   ***********************************************/
}



strcpy -- Copy Strings
strncpy -- Copy Strings
wcscpy -- Copy Wide-Character Strings
wcsncpy -- Copy Wide-Character Strings
<string.h>