Ali Sepehri-Amin Ali Sepehri-Amin - 3 years ago 176
C++ Question

Pointer truncation from 'BYTE *' to 'ULONG'

I tried to write a simple filter driver for windows, When I want to build the project, Visual Studio gives me the following warning:

Warning C4311 'type cast': pointer truncation from 'BYTE *' to 'ULONG'

and Error:
C2220 warning treated as error - no 'object' file generated

This is my code:

BOOLEAN GetAllBufferFromChunkedFormat(STREAM_EDIT_PARAMETERS* params, BYTE**
if (!CheckPointer(params) || !CheckPointer(dataBuffer))
return FALSE;
BYTE* iterator = params->dataStart + params->contentStart;
params->currentContentLength = 0;
UINT currentChunkLength = 0;
while ((ULONG)iterator - (ULONG)params->dataStart < params->streamEditor->dataLength) //calculate total length
currentChunkLength = strtol(iterator, &iterator, 16);
iterator += s_chunksSeparatorLength + currentChunkLength + s_chunksSeparatorLength;

The warning shows at line:

while ((ULONG)iterator - (ULONG)params->dataStart < params->streamEditor->dataLength)

What is the problem? and Why ?

Answer Source

A LONG type is 4 byte wide, while a pointer type such as BYTE* has the width of the architecture, i.e. 32 bits or 4 byte on a x86 platform, and 64bits (8byte) on an x64 architecture. Hence this would compile fine on a x86 platform, but gives warnings (that are treated as errors) on a 64 bit platform.

For the x64 architecture, the correct conversion would be towards numerical type "LONG LONG" or UINT64 and similar types, or if you really do not care you can static_cast (x) the value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download