I'm building a 64bit C++ code on VS 2015.
DWORD blockLength;
blockLength = strlen((LPCSTR)sourceVar); // sourceVar is of type Cstring, build warning here.
// Allocate memory.
defaultBuffer = new unsigned char[blockLength + 1];
sprintf_s(reinterpret_cast<char*>(defaultBuffer), (blockLength + 1), "%s", (LPCSTR)sourceVar);
// Decrypt data
if (!someMethod(someParameter, 0, 1, 0, defaultBuffer, &blockLength))
{
// Do something
}
When I run the code from HP-fortify, I don't see any build warnings or any fortify issues.
However, when I build the code separately, I see this warning on 2nd line -
warning C4267: '=': conversion from 'size_t' to 'DWORD', possible loss of data
Now, when I make these code changes -
blockLength = sourceVar.GetLength();
The build warning is gone. However, when I run this new code against HP-Fortify, I now see following error at sprintf_s line -
Buffer Overflow (Input Validation and Representation, Data Flow) - The function writes outside the bounds of allocated memory, which could corrupt data, cause the program to crash, or lead to the execution of malicious code.
In 64-bit mode a size_t will be 64-bits, but a DWORD will always be 32-bit... So assigning a 64-bits value to 32 bits value looses the top 32-bits of the size_t, hence the warning.
Why you only get it in release mode - no idea.