1

In the process to port my current 32 bit application to 64 bit, I have added the compiler option /we4302 (Refer the SO Question Clarification: Porting 32 to 64 bit and the suggested answer by Hans Passant), I encountered a scenario where an ATLMFC Include file seems to have pointer truncation.

c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\ATLMFC\INCLUDE\afxtempl.h
(163) : error C4302: 'type cast' : truncation from 'CControlBar *' to 'long'
c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\ATLMFC\INCLUDE\afxtempl.h
(163) : error C4302: 'type cast' : truncation from 'HMENU ' to 'long'

I was planning to add the compiler flag permanently to our build system, but if we have issues in MFC Includes, that would be a bad idea.

So My Question is

  1. Is the reported problem a false warning?
  2. If this indeed results a Pointer Truncation, what is the suggested solution
  3. Is it a bad idea to add the compiler option /we4302 in the build system?
Community
  • 1
  • 1
Abhijit
  • 62,056
  • 18
  • 131
  • 204
  • With the MS compiler a `long` is 32-bits in both 32- and 64-bit mode. This means that the pointer will not fit, which definitely is a problem. – Bo Persson Mar 02 '13 at 16:43
  • On the other hand, line 163 seems to compute a hash value `ldiv_t HashVal = ldiv((long)(ARG_KEY)key, 127773);` where key already is of type ARG_KEY, so I really don't know. – Bo Persson Mar 02 '13 at 16:50

2 Answers2

2

If you open the afxtempl.h header file, you'll find the following code at line 163:

template<class ARG_KEY>
AFX_INLINE UINT AFXAPI HashKey(ARG_KEY key)
{
    // (algorithm copied from STL hash in xfunctional)
    ldiv_t HashVal = ldiv((long)(ARG_KEY)key, 127773); // *** error is on this line
    HashVal.rem = 16807 * HashVal.rem - 2836 * HashVal.quot;
    if (HashVal.rem < 0)
        HashVal.rem += 2147483647;
    return ((UINT)HashVal.rem);
}

The cast to (long) is inside a method that calculates a hash code. Although it's not ideal (because it could potentially cause hash collisions), it's not an error to throw away the top 32 bits when calculating a hash code. Thus, this is a spurious warning that you can ignore.

I would use /we4302 on your local development box to find and fix all real errors; there may end up being just too many false positives to enable it on the build server.

Bradley Grainger
  • 27,458
  • 4
  • 91
  • 108
0

To add to Bradley's answer, I found:

A Comprehensive comparison of the MFC & ATL changes in VS 2015 RC compared to Visual Studio 2013 Update 4 (Part 1)

... ...

  • afxtempl.h

    Line 164: The template function HashKey now supresses the C4311 compiler error

So it seems they finally fixed it in VS 2015.

Community
  • 1
  • 1
Martin Ba
  • 37,187
  • 33
  • 183
  • 337