Odd behavior from TinyXML++ - c++

Hoping some of you TinyXML++ people can help me out. Really, since you recomended to me before I think you owe me ;)
I have the following code:
//ticpp::Iterator< ticpp::Element > child( "SetPiece" );
ticpp::Iterator< ticpp::Node > child("SetPiece");
GLuint lc_SPieces = 0;
for(child = child.begin( this ); child != child.end(); child++ )
{
lc_SPieces++;
}
If I use the top declaration for child I get the error:
Unhandled exception at 0x7c812aeb in
Drawing.exe: Microsoft C++ exception:
__non_rtti_object # 0x0012f7b4.
And I get it in dbgheap.c at this line:
pvBlk = _heap_alloc_dbg(nSize, nBlockUse, szFileName, nLine);
What's weird is it works with Node, and I know that there are elements in there(I checked using the TinyXML iteration methods).
Has anyone run into this before?

just poking in the dark, i don't know tinyxml, but it seems that a dynamic_cast went wrong.
If you dynamic_cast<> a pointer, you get a NULL-pointer on failure. However, if you cast to a reference type, there is no concept of a NULL-reference, so the runtime throws this exception (or bad_type). MSDN on dynamic_cast, and why it can go wrong
The line you pasted for the exception to occur does not help to clear up the situation, since it identifies the symptom rather than the cause.
Try to identify the cast that went wrong, you should be able to find it if you walk up the stack and find the last method in tinyxml libs or headers. Then you can decide whether tinyxml is worng, or you just applied it the wrong way.
good luck!

__non_rtti_object is generated by the dynamic_cast operator if the passed pointer or reference does not point to a polymorphic object, but to some garbage instead. Maybe the object had been deleted earlier.
Step through the code in the debugger and check where the dynamic_cast is used and what is passed to it.
hth
Paavo

Project -> Properties -> C/C++ -> Language -> Enable Run-Time Type Info

Related

Converting CFString to CFStringRef and CFErrorRef to CFError in c++

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()?

When should I use if(!someVar) vs assert()?

I always see some sort of variation of this statement:
if(!someVar)// or whatever expression
{
someVar = new type; //or however the programmer wants to handle it
}
within code. My question is when should someone favor this method of error checking over an assert()? What are some specific examples? In my mind, assert() is probably the safer choice most of the time as you should often be asking yourself why a null or wrong value was passed to the variable in the first place. In this light then, should you ever use the if(!expr) statement?
For background I'm working specifically in C++ and with the assert.h header.
In the code sample you provided, the programmer is checking someVar, and changing it if someVar evaluates to boolean false. Within the concept of error checking, you can consider this a recoverable error (the error can be resolved by changing the value of someVar)
With an Assert, you are making the statement that someVar MUST be true, or something is wrong that you cannot recover from. Typically this is only run in debug builds, and the program will exit if the condition is false.
Well, assert will crash the program if an error occurs. However, you don't always want that. You might, for example, want to open a dialog box that tells the user about an error and gives them a chance to save their work.
A common choice for error handling is to throw an exception. Exceptions are great, because they can be caught, but if they aren't caught, they still crash the program just like an assert.

FMOD_System_CreateSound runtime error

I'm using FMOD in my c++ project. There are no errors or warning when building, however when debugging; I get the following runtime error from the FMOD_System_CreateSound function:
Unhandled exception at 0x008e3f56 in Audio_Demo.exe: 0xC0000005: Access violation reading location 0xfdfdfdfd.
Here is the function call:
FMOD_System_CreateSound(system, filename.c_str(), FMOD_DEFAULT, NULL, &sample->sample);
Where, system is a pointer to an FMOD_SYSTEM object, sample is a helper class and sample->sample is a pointer to an FMOD_SOUND object.
If it's any help; in the project I have each of the arguments on a separate line and the error seems to occur at the final argument (sample->sample).
Thanks in advance for any help.
\,,/[>.<]\,,/
Spent the whole day scratching my head about this and only just decided to post on here for help. As luck would have, a bit more digging around and I realised my mistake.
I hadn't properly initialised my helper class containing the FMOD_SOUND object pointer, so it was null and thus threw an error. Just switching around a couple of lines of code in my initialiser function sorted this (i.e. my helper class was intialised before FMOD_System_CreateSound was called)
Figured I'd post the solution I found as I can't stand it when a poster asks a question; figures it out and says "Ah, it's alright. I solved it!" without sharing the answer with the rest of the world.
Hopefully, this will help someone having a similar problem. If not, then please comment and I'll try to clarify further.
\,,/[>.<]\,,/

Better handling of missing/wrong key in boost::program_options

Is there a way to know which key was involved when a call like the following fails ?
boost::program_options::variables_map vm;
...
int foo_bar = vm["some_key"].as<int>();
If the key is missing from the map, or is not convertible to int, I get a rather uninformative bad_any_cast, and I can't know any of the following:
the key involved
the stored value, or even if it's there.
the types involved
I can't find of any solution that doesn't involve either modifying the boost header or wrapping every call to the above in a try..catch block.
I think it's a common issue, so maybe someone else knows a better approach.
Marco,
there's no way to get better diagnostics without modifying the library.
However, please note that in general, I am not sure exceptions in this case are supposed to be very detailed:
- If you use wrong type to access variable, you've got a coding error. You can easily track that down with a debugger
- If you access a variable that does not exist, you either need to if vm.count, or use default value. Again, it's probably a coding error best solved using a debugger.
I agree that bad_any_cast is something that can be improved, but it does not seem that exception that can be reported to user should be a goal here, where exceptions are result of coding error.

In C++ what are the benefits of using exceptions and try / catch instead of just returning an error code?

I've programmed C and C++ for a long time and so far I've never used exceptions and try / catch. What are the benefits of using that instead of just having functions return error codes?
Possibly an obvious point - a developer can ignore (or not be aware of) your return status and go on blissfully unaware that something failed.
An exception needs to be acknowledged in some way - it can't be silently ignored without actively putting something in place to do so.
The advantage of exceptions are two fold:
They can't be ignored. You must deal with them at some level, or they will terminate your program. With error code, you must explicitly check for them, or they are lost.
They can be ignored. If an error can't be dealt with at one level, it will automatically bubble up to the next level, where it can be. Error codes must be explicitly passed up until they reach the level where it can be dealt with.
The advantage is that you don't have to check the error code after each potentially failing call. In order for this to work though, you need to combine it with RAII classes so that everything gets automatically cleaned up as the stack unwinds.
With error messages:
int DoSomeThings()
{
int error = 0;
HandleA hA;
error = CreateAObject(&ha);
if (error)
goto cleanUpFailedA;
HandleB hB;
error = CreateBObjectWithA(hA, &hB);
if (error)
goto cleanUpFailedB;
HandleC hC;
error = CreateCObjectWithA(hB, &hC);
if (error)
goto cleanUpFailedC;
...
cleanUpFailedC:
DeleteCObject(hC);
cleanUpFailedB:
DeleteBObject(hB);
cleanUpFailedA:
DeleteAObject(hA);
return error;
}
With Exceptions and RAII
void DoSomeThings()
{
RAIIHandleA hA = CreateAObject();
RAIIHandleB hB = CreateBObjectWithA(hA);
RAIIHandleC hC = CreateCObjectWithB(hB);
...
}
struct RAIIHandleA
{
HandleA Handle;
RAIIHandleA(HandleA handle) : Handle(handle) {}
~RAIIHandleA() { DeleteAObject(Handle); }
}
...
On first glance, the RAII/Exceptions version seems longer, until you realize that the cleanup code needs to be written only once (and there are ways to simplify that). But the second version of DoSomeThings is much clearer and maintainable.
DO NOT try and use exceptions in C++ without the RAII idiom, as you will leak resources and memory. All your cleanup needs to be done in destructors of stack-allocated objects.
I realize there are other ways to do the error code handling, but they all end up looking somewhat the same. If you drop the gotos, you end up repeating clean up code.
One point for error codes, is that they make it obvious where things can fail, and how they can fail. In the above code, you write it with the assumption that things are not going to fail (but if they do, you'll be protected by the RAII wrappers). But you end up paying less heed to where things can go wrong.
Exception handling is useful because it makes it easy to separate the error handling code from the code written to handle the function of the program. This makes reading and writing the code easier.
return an error code when an error condition is expected in some cases
throw an exception when an error condition is not expected in any cases
in the former case the caller of the function must check the error code for the expected failure; in the latter case the exception can be handled by any caller up the stack (or the default handler) as is appropriate
Aside from the other things that were mentioned, you can't return an error code from a constructor. Destructors either, but you should avoid throwing an exception from a destructor too.
I wrote a blog entry about this (Exceptions make for Elegant Code), which was subsequently published in Overload. I actually wrote this in response to something Joel said on the StackOverflow podcast!
Anyway, I strongly believe that exceptions are preferable to error codes in most circumstances. I find it really painful to use functions that return error codes: you have to check the error code after each call, which can disrupt the flow of the calling code. It also means you can't use overloaded operators as there is no way to signal the error.
The pain of checking error codes means that people often neglect to do so, thus rendering them completely pointless: at least you have to explicitly ignore exceptions with a catch statement.
The use of destructors in C++ and disposers in .NET to ensure that resources are correctly freed in the presence of exceptions can also greatly simplify code. In order to get the same level of protection with error codes you either need lots of if statements, lots of duplicated cleanup code, or goto calls to a common block of cleanup at the end of a function. None of these options are pleasant.
Here's a good explanation of EAFP ("Easier to Ask for Forgiveness than Permission."), which I think applies here even if it's a Python page in Wikipedia. Using exceptions leads to a more natural style of coding, IMO -- and in the opinion of many others, too.
When I used to teach C++, our standard explanation was that they allowed you to avoid tangling sunny-day and rainy-day scenarios. In other words, you could write a function as if everything would work ok, and catch the exception in the end.
Without exceptions, you would have to get a return value from each call and ensure that it is still legitimate.
A related benefit, of course, is that you don't "waste" your return value on exceptions (and thus allow methods that should be void to be void), and can also return errors from constructors and destructors.
Google's C++ Style Guide has a great, thorough analysis of the pros and cons of exception use in C++ code. It also indicates some of the larger questions you should be asking; i.e. do I intend to distribute my code to others (who may have difficulty integrating with an exception-enabled code base)?
Sometimes you really have to use an exception in order to flag an exceptional case. For example, if something goes wrong in a constructor and you find it makes sense to notify the caller about this then you have no choice but to throw an exception.
Another example: Sometimes there is no value your function can return to denote an error; any value the function may return denotes success.
int divide(int a, int b)
{
if( b == 0 )
// then what? no integer can be used for an error flag!
else
return a / b;
}
The fact that you have to acknowledge exceptions is correct but this can also be implemented using error structs.
You could create a base error class that checks in its dtor whether a certain method ( e.g. IsOk ) has been called. If not, you could log something and then exit, or throw an exception, or raise an assert, etc...
Just calling the IsOk on the error object without reacting to it, would then be the equivalent of writing catch( ... ) {}
Both statement would display the same lack of programmer good will.
The transport of the error code up to the correct level is a greater concern. You would basically have to make almost all methods return an error code for the sole reason of propagation.
But then again, a function or method should always be annotated with the exceptions it can generate. So basically you have to same problem, without an interface to support it.
As #Martin pointed out throwing exceptions forces the programmer to handle the error. For example, not checking return codes is one of the biggest sources of security holes in C programs. Exceptions make sure that you handle the error (hopefully) and provide some kind of recover path for your program. And if you choose to ignore an exception rather than introduce a security hole your program crashes.