Rahul Rahul - 8 days ago 6
C++ Question

_snprintf_s invokes [applicaiton].exe has triggered a breakpoint

_snprintf works ok. But why _snprintf_s triggered the breakpoint. Is there any mistake/ or i am missing something very important.

std::string hash_sha256_sa(const std::string source)
{
const int HASH_STRING = 64;
const int HASH_RAW = 32;

unsigned char _hash[HASH_RAW];
memset(_hash, 0, HASH_RAW);

sha256(_hash, (unsigned char*)&source[0], (unsigned long)source.length());

std::string str(HASH_STRING, 0);

for (int i = 0; i < HASH_RAW; ++i)
{
//_snprintf_s(&str[i * 2], HASH_STRING, _TRUNCATE, "%02X", _hash[i]); //Failed

//_snprintf(&str[i * 2], HASH_STRING,"%02X", _hash[i]); //Works
}

return str;
}


Second variant provide the same result. _snprintf works ok. but _snprintf_s results following error


Run-Time Check Failure #2 - Stack around the variable 'buffer' was
corrupted.


std::string hash_sha256_sa(const std::string source)
{
const int HASH_STRING = 64;
const int HASH_RAW = 32;

unsigned char _hash[HASH_RAW];
memset(_hash, 0, HASH_RAW);

sha256(_hash, (unsigned char*)&source[0], (unsigned long)source.length());

char buffer[HASH_STRING + 1];

for (int i = 0; i < HASH_RAW; ++i)
{
_snprintf_s(&buffer[i * 2], _countof(buffer), _TRUNCATE, "%02X", _hash[i]);

//_snprintf(&buffer[i * 2], _countof(buffer), "%02X", _hash[i]);

}

std::string str(buffer);
return str;
}

Answer

You are not sending buffer to _snprintf_s, rather you are sending &buffer[i * 2]. At each increment, the available size for &buffer[i * 2] will decrease by 2. So change to the 2nd parameter as follows:

_snprintf_s(&buffer[i * 2], _countof(buffer) - i * 2, _TRUNCATE, "%02X", _hash[i]);
Comments