[英]Warning - Conversion from size_t to DWORD, possible loss of data
I'm building a 64bit C++ code on VS 2015. 我正在VS 2015上构建64位C ++代码。
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. 当我从HP-fortify运行代码时,看不到任何构建警告或任何强化问题。
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 - 但是,当我针对HP-Fortify运行此新代码时,现在在sprintf_s行看到以下错误-
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. 在64位模式下,size_t将为64位,但DWORD将始终为32位...因此,将64位值分配给32位值将失去size_t的前32位,因此出现警告。
Why you only get it in release mode - no idea. 为什么只在发布模式下获得它-不知道。
blockLength = static_cast<int>(strlen((LPCSTR)sourceVar));
Using static_cast fixed the issue. 使用static_cast解决了该问题。 There are no errors in HP Fortify and no warnings while building. HP Fortify中没有错误,构建时也没有警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.