xref: /reactos/sdk/lib/ucrt/string/wcsdup.cpp (revision 53d808d2)
1 //
2 // wcsdup.cpp
3 //
4 //      Copyright (c) Microsoft Corporation.  All rights reserved.
5 //
6 // Defines _wcsdup() and _wcsdup_dbg(), which dynamically allocate a buffer and
7 // duplicate a string into it.
8 //
9 // These functions allocate storage via malloc() or _malloc_dbg().  The caller
10 // is responsible for free()ing the returned array.  If the input string is null
11 // or if sufficient memory could not be allocated, these functions return null.
12 //
13 #include <corecrt_internal.h>
14 #include <malloc.h>
15 #include <string.h>
16 
17 #ifdef _DEBUG
18 
19 extern "C" wchar_t* __cdecl _wcsdup(wchar_t const* const string)
20 {
21     return _wcsdup_dbg(string, _NORMAL_BLOCK, nullptr, 0);
22 }
23 
24 extern "C" wchar_t* __cdecl _wcsdup_dbg(
25     wchar_t const* const string,
26     int            const block_use,
27     char const*    const file_name,
28     int            const line_number
29     )
30 
31 #else // ^^^ _DEBUG ^^^ // vvv !_DEBUG vvv //
32 
33 extern "C" wchar_t* __cdecl _wcsdup(
34     wchar_t const* string
35     )
36 
37 #endif // !_DEBUG
38 {
39     if (string == nullptr)
40         return nullptr;
41 
42     size_t const size_in_elements = wcslen(string) + 1;
43 
44 #ifdef _DEBUG
45     wchar_t* const memory = static_cast<wchar_t*>(_malloc_dbg(
46         size_in_elements * sizeof(wchar_t),
47         block_use,
48         file_name,
49         line_number));
50 #else
51     wchar_t* const memory = static_cast<wchar_t*>(malloc(
52         size_in_elements * sizeof(wchar_t)));
53 #endif
54 
55     if (memory == nullptr)
56         return nullptr;
57 
58     _ERRCHECK(wcscpy_s(memory, size_in_elements, string));
59     return memory;
60 }
61