Problem on dword ptr[…] with visual studio 2010-Collection of common programming errors

I’m trying to compile a program which worked with the compiler of Visual C++ 6.0. Now, I’m compiling it using the compiler of Visual Studio 2010. It compiles but my program crashes on assignment of a variable:

sapHigh = ctx->saphigh;

In assembler code (using Visual Studio Debugger), this instruction is decomposed by:

00410DF3  mov         eax,dword ptr [ctx]  
00410DF6  mov         ecx,dword ptr [eax+20h]  
00410DF9  mov         dword ptr [sapHigh],ecx 

The instruction “mov eax, dword ptr[ctx]” return 0x00000000 in eax and the program crashes. But the debugger can see the real value of ctx pointer which is “0x0172287a”. If I change the value of the eax register with its real value, “0x0172287a”, the program still working fine until the next assignment.

Does anybody know why this instruction doesn’t work ? Is this a problem with compilation options ?

Thank you for your help.

  1. That’s a long gap of 10-12 years. I recommend you compile the program in VC10 with ALL compiler warnings enabled, and attempt to remove all of them. It includes all warnings related to deprecated stuff, 64-bit warnings, performance warnings, and C++ compliant warnings.

  2. Sounds like the memory for the variable ctx is not longer valid. If ctx is for example part of some dynamically allocated struct that got freed earlier, or if it’s a reference or pointer to an out-of-scope stack variable, all kinds of undefined behaviors can happen.

    Using invalid memory might not crash if (by chance) no other functions overwrote that memory, but using a different compiler and a different runtime library can easily lead to different results.

  3. What if you try lea eax, dword ptr[ctx] ?

    Also I’ve seen problems like that happen if the pointer to the array is passed to a function. When the array is defined within a function everything’s fine.

Originally posted 2013-11-09 22:49:26.