2

I don't know why but this code below gives this error in debug mode when compiling in 64-bit:

Unhandled exception at 0x000000013f488f55 in OpenGL.exe: 0xC0000005: Access violation reading location 0x000000053f4d9778.

However it works perfectly fine in release mode and both debug and release when compiled in 32-bit! Help is very much appreciated.

I'm using Visual Studio 2010.

float g_History[20] = { 0.0f };
const float g_WeightModifier = 0.25f;

void CInput::SmoothMouseMovement()
{
    if(!m_SmoothMouse) return;

    for(UINT i = 0; i < 10; i++)
    {
        g_History[i * 2] = g_History[(i - 1) * 2]; // This line gives the error
        g_History[i * 2 + 1] = g_History[(i - 1) * 2 + 1];
    }

    g_History[0] = m_MouseState.X;
    g_History[1] = m_MouseState.Y;

    float AverageX = 0.0f;
    float AverageY = 0.0f;
    float AverageTotal = 0.0f;
    float WeightModifier = 1.0f;

    for(UINT i = 0; i < 10; i++)
    {
        AverageX += g_History[i * 2] * WeightModifier;
        AverageY += g_History[i * 2 + 1] * WeightModifier;
        AverageTotal += 1.0f * WeightModifier;
        WeightModifier *= g_WeightModifier;
    }

    m_MouseState.X = AverageX / AverageTotal;
    m_MouseState.Y = AverageY / AverageTotal;
}
Traxmate
  • 105
  • 1
  • 6
  • Any decent debugging tool would have pointed out the exact line. I recommend starting to use one. – Christian Neverdal Jan 01 '12 at 02:29
  • @ChristianJonassen Can you recommend me one? So far I've only been using the one in Visual Studio. – Traxmate Jan 01 '12 at 03:53
  • Running Debug in Visual Studio (at least version 10.0) halts execution at the offending line and asks if I want to break or continue. If you are unable to use that, another general tip is using asserts to check it an array is within bounds. – Christian Neverdal Jan 01 '12 at 07:33

1 Answers1

6

The first time through your loop, g_History[(i - 1) * 2] is going to be the equivalent of g_History[-2], which is obviously a bad access. It's just coincidence on how memory is arranged with 32v64 and debug v release. That line is an error regardless of whether your app is crashing or not.

Jason Coco
  • 77,985
  • 20
  • 184
  • 180
  • 2
    Indeed, debug mode is probably going to some lengths to make these errors more obvious. In release mode you're just reading garbage data. – bdonlan Jan 01 '12 at 02:22
  • Oh wow thanks can't believe I didn't notice that... Didn't really pay any more attention to the code after I implemented it until I started compiling in 64-bit. – Traxmate Jan 01 '12 at 03:47