Search code examples
c#.netinteropintptr

IntPtr addition


So from what I can tell, every managed example of IntPtr addition I have found is WRONG.

For example: http://www.atalasoft.com/cs/blogs/stevehawley/archive/2006/10/16/10987.aspx

My thought being, that if IntPtr is at (or near) int32.MaxValue on a 32-bit system, and you add an offset which overflows int32, isn't that still a valid memory address (as it would be valid in uint32, and would be represented by a negative number in IntPtr)?!

I believe the code should be something like:

public static IntPtr Offset(IntPtr src, int offset)
{
    switch (IntPtr.Size) {
    case 4:
        return new IntPtr((int)((uint)src + offset));
    case 8:
        return new IntPtr((long)((ulong)src + offset));
    default:
        throw new NotSupportedException("Not supported");
    }
}

Am I crazy?

Does anyone have a tried and true IntPtr addition example?


Solution

  • I think the point is that if you overflow an int, you still get the appropriate value. Try this:

    //-2147483645
    Console.WriteLine( int.MaxValue + 4 );
    
    //2147483651
    Console.WriteLine( (uint)(int.MaxValue + 4) );
    

    Given that int.MaxValue is 2147483647, casting the overflowed negative number to uint does in fact give the right value.