首页 > 解决方案 > VC++ 中更安全的字符串复制功能,但如何处理 TCHAR*?

问题描述

我正在修复MS 建议的所有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++

解决方案


我根据@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);

推荐阅读