【发布时间】:2013-05-23 22:47:35
【问题描述】:
我在我正在处理的 Visual C++ 项目中使用TCHAR,其定义如下所示:
#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;
这是正确的想法还是我错过了什么?
【问题讨论】:
-
buff[size * sizeof(TCHAR) / sizeof(char)]? -
@Luchian Grigore:不,尺寸是我真正要问的 - 我想了解应该如何计算尺寸的值,基于我知道将传递哪些数据的事实它(数据:
"%s (ID: %i)", res->name(), res->id())。
标签: c++ c visual-c++ memory-management buffer-overflow