THE ANSWER ACCEPTED GAVE ME THE CORRECT EXPLANATION OF THE PROBLEM. I ALSO EDITED THE QUESTION PUTTING THE ANSWER POINT BY POINT IN CAPITAL LETTERS TO MAKE IT CLEARER
I have a c++ code in MacOSX, that use a bit of CoreFoundation.
I use the following function CFPropertyListCreateWithData in my code that takes a CFErrorRef *error as one of its parameters. Well, I create CFErrorRef myError and pass it as &myError
First problem: I think there is a bug in the Documentation, because it gives me some good data as result, but the error is NOT NULL. If I have an error, the data should be NULL, shouldn't it? Or did I misunderstand the documentation?
FIRST SOLUTION: THE ERROR IS UNDEFINED IF THERE IS NO ERROR, SO I HAD TO CHECK THE ERROR ONLY IF THE DATA WERE NULL. MOREOVER I WAS RELEASING USING CFRelease A UNDEFINED OBJECT, THE ERROR, THAT CAUSED MY PROGRAM TO CRASH WITH A SEGMENTATION FAULT
Second problem: I want to check which is the error.
Well I get into this function CFErrorCopyFailureReason, doc here,
but it takes a CFError and not a CFErrorRef, and gives me a CFString. Then, how can I transform my CFErrorRef to CFError?
SECOND SOLUTION: NOSENSE QUESTION, I WAS READING THE DOCUMENTATION OF SWIFT AND NOT OF OBJECTIVE-C
Third problem: the function CFErrorCopyFailureReason gives me a CFString, but I do not know where the CFString is defined! it is not in CoreFoundation/CoreFoundation.h and neither in CoreFoundation/CFString.h, and I have a undefined type error when I try to compile.
Then: In which file is CFString defined? Can I convert it to CFStringRef, and how can I do it?
THIRD SOLUTION: NOSENSE QUESTION, I WAS READING DOCUMENTATION OF SWIFT AND NOT OF OBJECTIVE-C
Fourth problem: with the code I have, if I use CFStringRef and CFErrorRef instead of CFString and CFError, it compiles, but then I have a NSInvalidArgumentException. Shouldn't I have an error at compilation time? I would not like a RunTimeException...
FOURTH SOLUTION: AS THE ANSWER MADE ME UNDERSTAND, I HAD TO CHECK THE ERROR ONLY IF THE DATA WAS NULL. IN THAT CASE I WAS CHECKING A ERROR WITH UNDEFINED DATA THAT GAVE ME THE INVALID ARGUMENT EXCEPTION. OBVIOUSLY, SINCE THE PROBLEM WAS UNDEFINED VALUE IN THE ERROR, THIS IS A RUNTIME EXCEPTION
Well, to conclude, I just want to read and write a Info.plist file in my c++ application. I take inspiration from this, Saving and Restoring Property Lists, sample code and modified it quite a bit. If you have a working sample how to read and modify a Info.plist file, please tell me :) but without using PlistBuddy or other tools please, only c++ API.
TO CONCLUDE: THE SAMPLE CODE WORKS WELL, I JUST MISUNDERSTOOD THE DOCUMENTATION
Thanks to everybody
I think you are misunderstanding the documentation for CFPropertyListCreateWithData(): if it succeeds, the return value is non-NULL, and what error points to is not defined. Don't worry about error unless CFPropertyListCreateWithData() returns NULL.
CFErrorCopyFailureReason() does take a CFErrorRef and return a CFStringRef. You might be looking at the Swift documentation for it, change the language to Objective-C on the top of the documentation page.
Which call is throwing the exception, CFPropertyListCreateWithData()?
I was following the official documentation for libsigc++-2.0 and I found this example:
class AlienDetector
{
public:
AlienDetector();
void run();
sigc::signal<void> signal_detected;
};
void warn_people()
{
cout << "There are aliens in the carpark!" << endl;
}
int main()
{
AlienDetector mydetector;
mydetector.signal_detected.connect( sigc::ptr_fun(warn_people) );
mydetector.run();
return 0;
}
As you can see both the run() function and the constructor for the AlienDetector class are not defined and therefore this code shouldn't compile ( but the doc takes for granted the fact that this code will work ).
Even more strange is the fact that if I define both run() and the constructor for the class, I can't see the effect of the library anyway, apparently the signal doesn't work and when run is called in the main no slot is activated.
I am forgetting about something here ? How this thing should be re-written ?
The documentation seems to be incomplete.
The most basic version of the code should look like:
AlienDetector::AlienDetector() {}
void AlienDetector::run() {
sleep(3); // wait for aliens
signal_detected.emit(); // panic
}
I've posted a fully functional make-based example on github, example1.cpp is the first example, example2.cpp is one using a member function.
To be more precise, that particular page of documentation is correct and presented as intended, but with a key link missing. I'll get to what is missing after reviewing what is there. The code that is listed as one block in the question is presented as two blocks in the documentation:
Here's my class:
<first code block, which
declares AlienDetector>
Here's your code that uses it:
<second code block, which
defines warn_people() and
main()>
This split is an important detail. The learning scenario being presented is one where you have to write code that interfaces with a certain class. In this sort of scenario, the information you have to work with is the declaration of that class, not the implementation of it (the header file, not the source). Hence, the first code block provides the declaration without code for the functions. The presentation appropriately leaves out the details that you should ignore at the moment.
The omission comes a bit further down the page:
To compile this example, use:
g++ example1.cc -o example1 `pkg-config --cflags --libs sigc++-2.0`
Hold on—"example1.cc"? What is that? You might notice that the page did not say how to create example1.cc. While it is somewhat natural to assume that one should copy the code from the page into this file, that is not what was intended. The author had intended that example1.cc be a pre-made file (with the missing function implementations) that would accompany the text. Somehow this file, and the others referenced later in the tutorial, never made it into the published product.
This omission has been known for a while (see some mail archives), but has not attracted the right sort of attention to fix it. (The tutorial was updated a few months after the emails I linked to, but apparently not to add the missing example files.) In the linked emails, the author provided a link to get the missing files, but in the decade+ since then, the link has expired.
Fortunately, Petesh has provided a longer-lived source for some example files in the older answer here. (As for me, I'm just being overly detailed and precise. Too bad I got lost when trying to figure out where this issue could be logged so that it could be addressed, or at least tracked.)
I'm working on a system which is designed to use the classes called error_code, error_condition, and error_category -- a scheme newly std: in C++11, altho at the moment I'm actually using the Boost implementation. I've read Chris Kholkoff's series of articles, three times now, and I think I understand how to create these classes generally.
My issue is that this system needs to handle plugins which exist in individual DLLs, and the plugins may issue errors. My original design was planning one system-specific error category that would encompass all the various error codes and a shortlist of specific error conditions that don't really map to the errno values. The problem here is that for the DLL to be able to use one of these error codes, it needs access to the sole instance of the error_category in the app. I'm handling this now by exporting a SetErrorCategory() function from each DLL, which works but is kinda icky.
The alternate solution I see is that each DLL has its own error category and codes, and if needed, its own conditions; I suspect this is more like what was envisioned for this library feature. But, I think this requires a comparison function in the main app's error scheme that knows about the plugins' error schemes and can check which of the app's conditions match the plugin's error. This seems even more prone to a bunch of problems, altho I haven't tried to implement it yet. I'm guessing I'd have to export the entire error scheme from the DLL, on top of all the actual logic.
Another way to do this, of course, is to just use numeric error codes from the DLL and stuff them into error objects on the app side. It has the advantage of simplicity for the plugin, but could lead to gotchas in the app (e.g., a function juggling objects from a couple different plugins needs to pay attention to the source of each error).
So my specific question is: of those three options, which would you use, and why? Which is obviously unworkable? And of course, is there a better way that hasn't occurred to me?
The solution I arrived at when working on this problem was to use predefined codes for the family of problem and user subcode selection along with inheritance for the specific type of error. With boost this lets me inherit the specific type by:
struct IOException : virtual std::exception, virtual boost::exception {};
struct EOFException : IOException {};
...
and leave the error code matching the predefined general errors like IOException. Thus I can have a general code range for each family of error:
namespace exception { namespace code {
UNKNOWN_EXCEPTION = 0;
IO_EXCEPTION = 100;
CONCURRENCY_EXCEPTION = 200;
...
}}
Then if someone wants a new error type they can inherit from a generic exception type that's already defined and the code that goes along with that error and specialize the exception by inheritance type and minor value (0-99). This also allows for try catch blocks to catch more specific error types while lettings more general versions of the exception pass to other control blocks. The user is then free to use the parent exception code or specify their own code which is within the family (parent = 100 -> child = 115). If the user just wants an IOError, without creating a new family of errors, they can just use the default family exception with no hassle. I found this gave the user flexibility without requiring OCD tracking of exception codes when they don't want it.
However this is by no means the end-all solution, as personal preference led my design choices here. I find the having too many error codes becomes confusing and that exception inheritance already encodes this information. Actually, in the system I described it's easy to strip out error codes entirely and just rely on exception inheritance, but many people prefer having a code assigned to each exception name.
I figured out another solution: Create one DLL that contains only my error_category implementation, and link to it from the app and from each plugin DLL. This gives them all access to the global category object, without having to explicitly pass that object from the app to the DLL.
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?
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.
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.
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.
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
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);
}
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.
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.
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.
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?
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).
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.
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.
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.
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.
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?
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).
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."
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.
Not the best answer but I just recompiled my code from scratch (rebuild in VS) and then the problem went away.