Error : The value of ESP was not properly saved across a function call.

Sometimes you may face such a error while executing your program written in C++: 
  
Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call.
or 
Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.


The above mentioned error you will get only if you are running program compiled in debug mode. If the program is compiled in release mode you will get Exception code: 0xc0000005 which is Access Violation exception. 


Cause of error:


Consider a situation,  you have declared one function with one calling convention ( for example __cdecl ). You do LoadLibrary, get the proc address, now if you are calling function with other  calling convention such as ( __stdcall ) by mistake. Function executed, your task completed sucessfully. Everything will work fine until  you try to use the return value of the function.


The error Access Violation occurred because you have declared function with __cdecl calling convention, means function has its own stack clean up code. And you are trying to access the function with __stdcall which means, function does not code to cleanup the stack, so compiler will insure that after function returns the callee will celanup the stack, which eventually means there are two stack cleaner exists. 
Now function execution will complete as expected but then the time will come to assign the value of return variable which is present in the ESP register due to two cleanup codes the second time asses to the ESP will be evaluated in the exception as register is already cleaned by one of the cleaner. 

No comments:

Post a Comment

Golang: Http POST Request with JSON Body example

Go standard library comes with "net/http" package which has excellent support for HTTP Client and Server.   In order to post JSON ...