using strcpy_s for TCHAR pointer (Microsoft Specific)

坚强是说给别人听的谎言 提交于 2021-02-19 01:34:26


I was wondering which is the correct way?

_tcscpy(tchar_pointer, _tcslen(tchar_pointer), _T("Hello World"));


_tcscpy(tchar_pointer, _tcsclen(tchar_pointer), _T("Hello World"));


_tcscpy(tchar_pointer, ???, _T("Hello World"));


the tchar pointer are coming from external, and my side has no idea how large the buffer referred by the pointer is

If this is so, then none of these do what you want.

The way all the "safe" functions work is that you tell them how big the target buffer is.

You don't know? You can't use those functions.

int buffer_size = _tcslen(xxx) * sizeof(TCHAR)

This will not work. All it will guarantee is that the string copied is not longer than whatever is already in the buffer. If the buffer has not been initialized, it will fail; if the buffer begins with a '\0', nothing will be copied; and so forth.


Assuming you are using _tcscpy_s and not _tcscpy, the second parameter should be the actual size of the array, and not the length of the currently contained string. For example:

TCHAR dest[20];
_tcscpy_s(dest, _countof(dest), _T("Hello"));

You can even use the 2-parameter version that will not require the size parameter:

_tcscpy_s(dest, _T("Hello"));

If tchar_pointer is actually a pointer and not an array (as implied by its name) you need to be very careful when determining what its actual capacity is. More context would be needed to suggest the right approach, but using the length of the contained string to compute the size of the buffer is almost certainly the wrong approach.


bara's answer is very important for you, because the correct answer differs from all of the ideas you listed. But bara didn't explain to you the difference between _tcslen and _tcsclen, so I'll do that.

In a Unicode compilation, _tcslen and _tcsclen will both count the number of TCHARs in the current value of the string. Each TCHAR is one wchar_t.

In a Multibyte compilation, _tcslen will count the number of TCHARs in the current value of the string. Each TCHAR is one char. But _tcsclen will count the number of multibyte characters in the current value of the string. Each multibyte character is one or more TCHARs, each multibyte character is one or more chars. Different multibyte characters can have different lengths, depending on the code page and the individual characters.


If tchar_pointer is a pointer (as opposed to an array) you are supposed to know yourself how big the pointed-to buffer is. If you don't know, you cannot find out from the raw pointer, strcpy_s doesn't help there.