我在TCHAR
我正在处理的 Visual C++ 项目中使用,其定义如下所示:
#ifdef _UNICODE
typedef wchar_t TCHAR;
#else
typedef char TCHAR;
#endif
我需要将一些数据放入缓冲区buff
:
char buff[size] = {0}; // how to declare the buffer size - what should be its value ?
sprintf(buff, "%s (ID: %i)", res->name(), res->id());
在哪里:
name()
返回TCHAR*
id()
返回int
如何计算size
实际需要的精确缓冲区容量的值(如果没有定义unicode,则较小,如果定义unicode,则较大)?另外我想保护自己免受缓冲区溢出的可能性,我应该使用什么样的保护?
更重要的是,我在这里将缓冲区声明为char
. 如果我将缓冲区声明为int
,大小值会有什么不同(即,如果与声明为 char 相比,则小 4 倍)?
更新
我部分基于 Mats Petersson 的回答得出的结论是:
size_t len;
const char *FORMAT;
#ifndef _UNICODE
len = strlen((char*)res->name());
FORMAT = "%s (ID: %i)";
#else
len = wcslen(res->name());
FORMAT = "%S (ID: %i)";
#endif
int size = 7 * sizeof(TCHAR) + /* place for characters inside format string */
len * sizeof(TCHAR) + /* place for "name" characters */
strlen(_itoa(id, ioatmp, 10)) * sizeof(TCHAR) + /* place for "id" digits */
1 * sizeof(TCHAR); /* zero byte(s) string terminator */
char *buff = new char[size]; /* buffer has to be declared dynamically on the heap,
* because its exact size is not known at compilation time */
sprintf(buff, FORMAT, name, id);
delete[] buff;
这是正确的想法还是我错过了什么?