【发布时间】:2016-08-22 21:11:17
【问题描述】:
我在 C++ 11 中使用sprintf 函数,方式如下:
std::string toString()
{
std::string output;
uint32_t strSize=512;
do
{
output.reserve(strSize);
int ret = sprintf(output.c_str(), "Type=%u Version=%u ContentType=%u contentFormatVersion=%u magic=%04x Seg=%u",
INDEX_RECORD_TYPE_SERIALIZATION_HEADER,
FORAMT_VERSION,
contentType,
contentFormatVersion,
magic,
segmentId);
strSize *= 2;
} while (ret < 0);
return output;
}
除了每次检查预留空间是否足够之外,还有更好的方法吗?为了将来添加更多东西的可能性。
【问题讨论】:
-
你在使用
snprintf吗?因为sprintf,如您的代码所示,无法确定缓冲区大小。snprintf也会返回所需的缓冲区大小,因此您可以将返回值 +1 用作新的strSize。 -
这段代码非常错误。
reserve不会改变字符串的大小,sprintf不会因为你写的越界而返回负数。你需要分配你需要的空间之前写出边界。