I am using sprintf
function in C++ 11, in the following way:
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;
}
Is there a better way to do this, than to check every time if the reserved space was enough? For future possibility of adding more things.
snprintf
? Becausesprintf
, as shown in your code, has no way to determine the buffer size.snprintf
would also return the required buffer size, so you could just use the returned value +1 as newstrSize
.reserve
does not change the size of the string, andsprintf
does not return negative just because you wrote out of bounds . You need to allocate the space you need before writing out of bounds.