Weird MSC 8.0 error: "The value of ESP was not properly saved across a function call..."
Asked Answered
T

20

54

We recently attempted to break apart some of our Visual Studio projects into libraries, and everything seemed to compile and build fine in a test project with one of the library projects as a dependency. However, attempting to run the application gave us the following nasty run-time error message:

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 pointer declared with a different calling convention.

We have never even specified calling conventions (__cdecl etc.) for our functions, leaving all the compiler switches on the default. I checked and the project settings are consistent for calling convention across the library and test projects.

Update: One of our devs changed the "Basic Runtime Checks" project setting from "Both (/RTC1, equiv. to /RTCsu)" to "Default" and the run-time vanished, leaving the program running apparently correctly. I do not trust this at all. Was this a proper solution, or a dangerous hack?

Tove answered 27/9, 2008 at 0:45 Comment(2)
Be ever so glad that the runtime caught this for you. If it didn't, the next thing the computer would do would be to shred the stack contents and crash in a horrendous way. (Debugging stack corruption is not for the faint-hearted.)Wherry
RE your update: No, it is not a proper solution. All you did was disable the checks. It's akin to burying your head in the sand. The problem is still there, and will undoubtedly blow up in your face later, when it'll be even harder to track down.Predicament
S
55

This debug error means that the stack pointer register is not returned to its original value after the function call, i.e. that the number of pushes before the function call were not followed by the equal number of pops after the call.

There are 2 reasons for this that I know (both with dynamically loaded libraries). #1 is what VC++ is describing in the error message, but I don't think this is the most often cause of the error (see #2).

1) Mismatched calling conventions:

The caller and the callee do not have a proper agreement on who is going to do what. For example, if you're calling a DLL function that is _stdcall, but you for some reason have it declared as a _cdecl (default in VC++) in your call. This would happen a lot if you're using different languages in different modules etc.

You would have to inspect the declaration of the offending function, and make sure it is not declared twice, and differently.

2) Mismatched types:

The caller and the callee are not compiled with the same types. For example, a common header defines the types in the API and has recently changed, and one module was recompiled, but the other was not--i.e. some types may have a different size in the caller and in the callee.

In that case, the caller pushes the arguments of one size, but the callee (if you're using _stdcall where the callee cleans the stack) pops the different size. The ESP is not, thus, returned to the correct value.

(Of course, these arguments, and others below them, would seem garbled in the called function, but sometimes you can survive that without a visible crash.)

If you have access to all the code, simply recompile it.

Severally answered 26/8, 2009 at 7:15 Comment(3)
+1 good explanation, would be perfect if you put some code examples to guide himDavenport
I had the same exception, but none of above were the cases. I was battling it for several hours until I finally narrowed down the problem to a function, that has an argument being pointer to member function of other class. Calling this function caused stack corruption. The solution to this kind of problem can be found here: #8677379Argilliferous
possibility 3 - mismatched names when getting a function pointer (perhaps via a call to getProcAddress("theWrongFuntionName"). This is what I did! What happened: I bound a pointer to the named function to a function-pointer prototype (via a typedef). Everything looks right - no compile errors, but you're calling the wrong function at runtime. I guess you have to be unlucky enough to mistype a name that actually exists in your dll, but isn't the one you want, otherwise you'll be saved and get null back from getProcAddress().Repeated
S
20

I read this in other forum

I was having the same problem, but I just FIXED it. I was getting the same error from the following code:

HMODULE hPowerFunctions = LoadLibrary("Powrprof.dll");
typedef bool (*tSetSuspendStateSig)(BOOL, BOOL, BOOL);

tSetSuspendState SetSuspendState = (tSuspendStateSig)GetProcAddress(hPowerfunctions, "SetSuspendState");

result = SetSuspendState(false, false, false); <---- This line was where the error popped up. 

After some investigation, I changed one of the lines to:

typedef bool (WINAPI*tSetSuspendStateSig)(BOOL, BOOL, BOOL);

which solved the problem. If you take a look in the header file where SetSuspendState is found (powrprof.h, part of the SDK), you will see the function prototype is defined as:

BOOLEAN WINAPI SetSuspendState(BOOLEAN, BOOLEAN, BOOLEAN);

So you guys are having a similar problem. When you are calling a given function from a .dll, its signature is probably off. (In my case it was the missing WINAPI keyword).

Hope that helps any future people! :-)

Cheers.

Saretta answered 26/7, 2010 at 8:7 Comment(2)
"In my case it was the missing WINAPI keyword" - That's not a keyword. It's a preprocessor symbol, that expands to the calling convention. A question on mismatched calling conventions should at least contain the term "calling convention".Grimaldi
this was exactly the issue i just was having with compound type or whatever its actual name is. i didn't know where to put WINAPI so just left it out when explicitly loading dll to get a D3D12GetDebugInterface(). I had messed around with arguments but it was exactly as you had said with the winapi.Talich
S
11

Silencing the check is not the right solution. You have to figure out what is messed up with your calling conventions.

There are quite a few ways to change the calling convetion of a function without explicitly specifying it. extern "C" will do it, STDMETHODIMP/IFACEMETHODIMP will also do it, other macros might do it as well.

I believe if run your program under WinDBG (http://www.microsoft.com/whdc/devtools/debugging/default.mspx), the runtime should break at the point where you hit that problem. You can look at the call stack and figure out which function has the problem and then look at its definition and the declaration that the caller uses.

Seigniorage answered 27/9, 2008 at 0:53 Comment(0)
C
6

I saw this error when the code tried to call a function on an object that was not of the expected type.

So, class hierarchy: Parent with children: Child1 and Child2

Child1* pMyChild = 0;
...
pMyChild = pSomeClass->GetTheObj();// This call actually returned a Child2 object
pMyChild->SomeFunction();          // "...value of ESP..." error occurs here
Clein answered 14/5, 2009 at 14:53 Comment(0)
R
5

I was getting similar error for AutoIt APIs which i was calling from VC++ program.

    typedef long (*AU3_RunFn)(LPCWSTR, LPCWSTR);

However, when I changed the declaration which includes WINAPI, as suggested earlier in the thread, problem vanished.

Code without any error looks like:

typedef long (WINAPI *AU3_RunFn)(LPCWSTR, LPCWSTR);

AU3_RunFn _AU3_RunFn;
HINSTANCE hInstLibrary = LoadLibrary("AutoItX3.dll");
if (hInstLibrary)
{
  _AU3_RunFn = (AU3_RunFn)GetProcAddress(hInstLibrary, "AU3_WinActivate");
  if (_AU3_RunFn)
     _AU3_RunFn(L"Untitled - Notepad",L"");
  FreeLibrary(hInstLibrary);
}
Rora answered 17/6, 2012 at 9:0 Comment(0)
F
3

I was getting this error calling a function in a DLL which was compiled with a pre-2005 version of Visual C++ from a newer version of VC (2008). The function had this signature:

LONG WINAPI myFunc( time_t, SYSTEMTIME*, BOOL* );

The problem was that time_t's size is 32 bits in pre-2005 version, but 64 bits since VS2005 (is defined as _time64_t). The call of the function expects a 32 bit variable but gets a 64 bit variable when called from VC >= 2005. As parameters of functions are passed via the stack when using WINAPI calling convention, this corrupts the stack and generates the above mentioned error message ("Run-Time Check Failure #0 ...").

To fix this, it is possible to

#define _USE_32BIT_TIME_T

before including the header file of the DLL or -- better -- change the signature of the function in the header file depending on the VS version (pre-2005 versions don't know _time32_t!):

#if _MSC_VER >= 1400
LONG WINAPI myFunc( _time32_t, SYSTEMTIME*, BOOL* );
#else
LONG WINAPI myFunc( time_t, SYSTEMTIME*, BOOL* );
#endif

Note that you need to use _time32_t instead of time_t in the calling program, of course.

Fructification answered 21/5, 2014 at 6:41 Comment(5)
Of course, you need to switch to 64-bit time_t sometime well before 2038 (en.wikipedia.org/wiki/Year_2038_problem) or whenever Windows 32-bit time wraps around, or sooner if your code deals with dates in the future using time_t. And of course, existing binaries will potentially get used for years into the future, so the "well before" is important.Meetinghouse
@PeterCordes For sure 64-bit time_t should be used only. However, that "should" doesn't help you when having a DLL using function signatures with 32-bit time_t.Fructification
I commented as a reminder that this solution will stop being viable in a few years, depending on product lifecycles. At some point you have to bite the bullet and discard unmaintainable legacy binary-only crap, or rebuild it from source if you have it. It's useful to know how to make your new software hobble itself to be binary-compatible with old crap (so I upvoted this), but it's worth reminding people that it's not a permanent long-term solution.Meetinghouse
@PeterCordes Of course this cannot be deemed as a long-term solution, but there exists software in the "real world" where rebuilding from source is not an option -- or you need to have a degree in "software archeology"... ;-) (Visual C 1.52, anyone?)Fructification
Yes, that's why I upvoted this answer, for useful specific details of how to hack around this ABI change until 2038 at the absolute latest. As well as detail of what one ABI change actually was.Meetinghouse
R
3

It's worth pointing out that this can also be a Visual Studio bug.

I got this issue on VS2017, Win10 x64. At first it made sense, since I was doing weird things casting this to a derived type and wrapping it in a lambda. However, I reverted the code to a previous commit and still got the error, even though it wasn't there before.

I tried restarting and then rebuilding the project, and then the error went away.

Require answered 13/3, 2018 at 17:45 Comment(1)
Agree with this poster. Always try fully rebuilding your project when you get weird unexpected errors from code that you aren't even working on. This kind of thing happens a lot when you build large projects with incremental linking and all of the other utilities of VS. Sometimes it messes up the linking and you get random errors like this one.Schifra
C
2

I was having this exact same error after moving functions to a dll and dynamically loading the dll with LoadLibrary and GetProcAddress. I had declared extern "C" for the function in the dll because of the decoration. So that changed calling convention to __cdecl as well. I was declaring function pointers to be __stdcall in the loading code. Once I changed the function pointer from __stdcall to__cdecl in the loading code the runtime error went away.

Cheyenne answered 10/1, 2015 at 19:35 Comment(0)
G
1

Are you creating static libs or DLLs? If DLLs, how are the exports defined; how are the import libraries created?

Are the prototypes for the functions in the libs exactly the same as the function declarations where the functions are defined?

Gina answered 27/9, 2008 at 0:55 Comment(0)
S
1

do you have any typedef'd function prototypes (eg int (*fn)(int a, int b) )

if you dom you might be have gotten the prototype wrong.

ESP is an error on the calling of a function (can you tell which one in the debugger?) that has a mismatch in the parameters - ie the stack has restored back to the state it started in when you called the function.

You can also get this if you're loading C++ functions that need to be declared extern C - C uses cdecl, C++ uses stdcall calling convention by default (IIRC). Put some extern C wrappers around the imported function prototypes and you may fix it.

If you can run it in the debugger, you'll see the function immediatey. If not, you can set DrWtsn32 to create a minidump that you can load into windbg to see the callstack at the time of the error (you'll need symbols or a mapfile to see the function names though).

Silent answered 27/9, 2008 at 1:2 Comment(0)
S
1

Another case where esp can get messed up is with an inadvertent buffer overflow, usually through mistaken use of pointers to work past the boundary of an array. Say you have some C function that looks like

int a, b[2];

Writing to b[3] will probably change a, and anywhere past that is likely to hose the saved esp on the stack.

Sulphonamide answered 27/9, 2008 at 3:32 Comment(0)
C
1

You would get this error if the function is invoked with a calling convention other than the one it is compiled to.

Visual Studio uses a default calling convention setting thats decalred in the project's options. Check if this value is the same in the orignal project settings and in the new libraries. An over ambitious dev could have set this to _stdcall/pascal in the original since it reduces the code size compared to the default cdecl. So the base process would be using this setting and the new libraries get the default cdecl which causes the problem

Since you have said that you do not use any special calling conventions this seems to be a good probability.

Also do a diff on the headers to see if the declarations / files that the process sees are the same ones that the libraries are compiled with .

ps : Making the warning go away is BAAAD. the underlying error still persists.

Carlitacarlo answered 28/9, 2008 at 18:13 Comment(0)
C
1

This happened to me when accessing a COM object (Visual Studio 2010). I passed the GUID for another interface A for in my call to QueryInterface, but then I cast the retrieved pointer as interface B. This resulted in making a function call to one with an entirely signature, which accounts for the stack (and ESP) being messed up.

Passing the GUID for interface B fixed the problem.

Collyrium answered 17/4, 2014 at 22:4 Comment(0)
O
1

In my MFC C++ app I am experiencing the same problem as reported in Weird MSC 8.0 error: “The value of ESP was not properly saved across a function call…”. The posting has over 42K views and 16 answers/comments none of which blamed the compiler as the problem. At least in my case I can show that the VS2015 compiler is at fault.

My dev and test setup is the following: I have 3 PCs all of which run Win10 version 10.0.10586. All are compiling with VS2015, but here is the difference. Two of the VS2015s have Update 2 while the other has Update 3 applied. The PC with Update 3 works, but the other two with Update 2 fail with the same error as reported in the posting above. My MFC C++ app code is exactly the same on all three PCs.

Conclusion: at least in my case for my app the compiler version (Update 2) contained a bug that broke my code. My app makes heavy use of std::packaged_task so I expect the problem was in that fairly new compiler code.

Overmuch answered 26/8, 2016 at 16:47 Comment(3)
Jumping to conclusions, eh? Had it occurred to you, that maybe, just maybe, there is a bug in your code, that is common enough for a library update to implement a fix? Without a minimal reproducible example and thorough analysis of the generated object code, this is just speculation.Grimaldi
@Grimaldi The notion that a respectable compiler vendor today would change their code to repair a compiler user’s misbehaving code is without merit. On the other hand, if you can find a flaw or weakness in my natural 3-PC experiment, I would like to know.Overmuch
"if you can find a flaw or weakness in my natural 3-PC experiment, I would like to know" - Uhm... easy. Undefined behavior, in your code, that happens to manifest itself in a reproducible way, with reproducible observable behavior. That would be one obvious explanation, if you don't buy the notion of a compiler vendor changing their support libraries, to address common bugs. None of that is very helpful, though, if we cannot see your minimal reproducible example, that demonstrates the issue. Something like this would do.Grimaldi
R
0

ESP is the stack pointer. So according to the compiler, your stack pointer is getting messed up. It is hard to say how (or if) this could be happening without seeing some code.

What is the smallest code segment you can get to reproduce this?

Reverent answered 27/9, 2008 at 0:53 Comment(0)
D
0

If you're using any callback functions with the Windows API, they must be declared using CALLBACK and/or WINAPI. That will apply appropriate decorations to make the compiler generate code that cleans the stack correctly. For example, on Microsoft's compiler it adds __stdcall.

Windows has always used the __stdcall convention as it leads to (slightly) smaller code, with the cleanup happening in the called function rather than at every call site. It's not compatible with varargs functions, though (because only the caller knows how many arguments they pushed).

Dm answered 27/9, 2008 at 10:40 Comment(0)
S
0

Here's a stripped down C++ program that produces that error. Compiled using (Microsoft Visual Studio 2003) produces the above mentioned error.

#include "stdafx.h"
char* blah(char *a){
  char p[1];
  strcat(p, a);
  return (char*)p;
}
int main(){
  std::cout << blah("a");
  std::cin.get();
}

ERROR: "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."

Shrievalty answered 24/5, 2012 at 21:16 Comment(1)
This code exhibits undefined behavior. There are at least 3 fatal bugs: 1 Accessing an uninitialized array (p). 2 writing past the end of an array (strcat). 3 Returning the address of a local (return p). There are numerous ways to trigger this run-time check. Posting random buggy code that does (sometimes) is not at all helpful, sorry.Grimaldi
L
0

I had this same problem here at work. I was updating some very old code that was calling a FARPROC function pointer. If you don't know, FARPROC's are function pointers with ZERO type safety. It's the C equivalent of a typdef'd function pointer, without the compiler type checking. So for instance, say you have a function that takes 3 parameters. You point a FARPROC to it, and then call it with 4 parameters instead of 3. The extra parameter pushed extra garbage onto the stack, and when it pops off, ESP is now different than when it started. So I solved it by removing the extra parameter to the invocation of the FARPROC function call.

Ludendorff answered 30/10, 2014 at 21:46 Comment(0)
W
0

Not the best answer but I just recompiled my code from scratch (rebuild in VS) and then the problem went away.

Wounded answered 2/3, 2017 at 10:12 Comment(0)
C
0

I resolved this issue by removing unnecessary SDK files which had old implementation and the system was looking into these old files rather than files from the associated component.

In sort, you may want to check if you have added a header include which actually exists in two places (i.e. in two different folders).

Comfrey answered 19/6, 2023 at 15:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.