在VC++中更安全的字符串复制函数,但如何处理TCHAR*?

问题描述 投票:0回答:1

我正在修正所有的 C4996警告 将sprintf替换为sprint_s将_tcscpy替换为_tcscpy_s。

不需要用TCHAR[]改变参数就可以工作。

TCHAR* test; // a string argument from CLR project
TCHAR target[100];
_tcscpy(target, test); 
_tcscpy_s(target, test); // both works fine.

但TCHAR*呢?我不知道TCHAR*的缓冲区大小会有多大。

TCHAR* test; // a string argument from CLR project
TCHAR* target;
_tcscpy_s(target, ???, test);

下面是我研究的内容。

但是没有解决方案。

c++ visual-c++
1个回答
0
投票

我根据@dxiv的建议自己写了一个答案。

TCHAR*改为TCHAR*。

TCHAR* src= new TCHAR[??]; // check whether it is initialized.
TCHAR* dest= new TCHAR[??];
const int BUFFER= _tsclen(src) + 1;
_tcscpy_s(dest, BUFFER, src);

TCHAR[]转换为TCHAR*。

TCHAR src[??] = _T("something...");
TCHAR* dest= new TCHAR[??];
const int BUFFER= _countof(src);
_tcscpy_s(dest, BUFFER, src);

从TCHAR[]到TCHAR[]。

TCHAR src[??] = _T("something...");
TCHAR dest[??] = _T("");
_tcscpy_s(dest, src);
© www.soinside.com 2019 - 2024. All rights reserved.