简体   繁体   中英

Warning - Conversion from size_t to DWORD, possible loss of data

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.

blockLength = static_cast<int>(strlen((LPCSTR)sourceVar));

Using static_cast fixed the issue. There are no errors in HP Fortify and no warnings while building.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM