_strdup, _wcsdup, _mbsdup

Duplicates strings.

Important

_mbsdup cannot be used in applications that execute in the Windows Runtime. For more information, see CRT functions not supported in Universal Windows Platform apps.

Syntax

char *_strdup(
   const char *strSource
);
wchar_t *_wcsdup(
   const wchar_t *strSource
);
unsigned char *_mbsdup(
   const unsigned char *strSource
);

Parameters

strSource
Null-terminated source string.

Return value

Each of these functions returns a pointer to the storage location for the copied string or NULL if storage can't be allocated.

Remarks

The _strdup function calls malloc to allocate storage space for a copy of strSource and then copies strSource to the allocated space.

_wcsdup and _mbsdup are wide-character and multibyte-character versions of _strdup. The arguments and return value of _wcsdup are wide-character strings. The arguments and return value of _mbsdup are multibyte-character strings. These three functions behave identically otherwise.

By default, this function's global state is scoped to the application. To change this behavior, see Global state in the CRT.

Generic-text routine mappings

TCHAR.H routine _UNICODE and _MBCS not defined _MBCS defined _UNICODE defined
_tcsdup _strdup _mbsdup _wcsdup

Because _strdup calls malloc to allocate storage space for the copy of strSource, it's good practice always to release this memory by calling the free routine on the pointer that's returned by the call to _strdup.

If _DEBUG and _CRTDBG_MAP_ALLOC are defined, _strdup and _wcsdup are replaced by calls to _strdup_dbg and _wcsdup_dbg, to allow for debugging memory allocations. For more information, see _strdup_dbg, _wcsdup_dbg.

Requirements

Routine Required header
_strdup <string.h>
_wcsdup <string.h> or <wchar.h>
_mbsdup <mbstring.h>

For more compatibility information, see Compatibility.

Example

// crt_strdup.c

#include <string.h>
#include <stdio.h>

int main( void )
{
   char buffer[] = "This is the buffer text";
   char *newstring;
   printf( "Original: %s\n", buffer );
   newstring = _strdup( buffer );
   printf( "Copy:     %s\n", newstring );
   free( newstring );
}
Original: This is the buffer text
Copy:     This is the buffer text

See also

String manipulation
memset, wmemset
strcat, wcscat, _mbscat
strcmp, wcscmp, _mbscmp
strncat, _strncat_l, wcsncat, _wcsncat_l, _mbsncat, _mbsncat_l
strncmp, wcsncmp, _mbsncmp, _mbsncmp_l
strncpy, _strncpy_l, wcsncpy, _wcsncpy_l, _mbsncpy, _mbsncpy_l
_strnicmp, _wcsnicmp, _mbsnicmp, _strnicmp_l, _wcsnicmp_l, _mbsnicmp_l
strrchr, wcsrchr, _mbsrchr, _mbsrchr_l
strspn, wcsspn, _mbsspn, _mbsspn_l