Expression: header->_block_use == block_use || header->_block_use ==
_CRT_BLOCK && block_use == _NORMAL_BLOCK
What does this mean? It has something to do with a header?
I found in my code where after I step over it returns the debug assertion failure, just this one line of code works in other projects.
Is there a linker setting or c/c++ setting that I have to remove?
The assertion that you are hitting is part of the Microsoft Visual C/C++ runtime libraries, specifically related to the debug heap. Calling malloc/free and using the new/delete operators leads to calls to the CRT heap functions, which perform internal consistency checks using these assertions.
It's very likely that the assertion is hit as a result of a memory safety bug, for example trying to delete a garbage pointer, double-free, etc. If you are unable to find it, the ASAN tool can help by keeping closer track of memory operations and raising errors when your code does invalid things. Without these close checks, mistakes in your code can corrupt a data structure, and the crash could occur much, much later in unrelated code.
For Visual Studio, it involves a few steps: the "C++ AddressSanitizer" feature must be installed using the Visual Studio installer, and the address sanitizer must be enabled in the project properties under C/C++ -> General.
Languages such as C and C++ offer an assert(...expression...) facility that is typically used during debugging ... and omitted from the final delivered product. The ..expression... being "something that should always be False."
If the expression turns out not to be False, then it throws a runtime exception containing the exact text of expression. Which is exactly what a developer would like to see, because: "the whole idea is that this should never, ever, ever happen!"
Ordinarily, published versions of applications are compiled in such a way that all of the assert() statements are ignored: they are "no-ops."
Related
We have a custom application we use built around VB/C++ code.
This code will run for days, weeks, months, without this throwing up an exception error.
I'm trying to learn more about how this error is thrown, and how to interpret (if you can) the error listed when an exception is thrown. I've googled some information and read the Microsoft provided error description, but I'm still stuck with the task of trouble shooting something that occurs once in a blue moon. There is no known set of interactions with the software that causes this and appears to happen randomly.
Is the first exception the root cause? Is it all the way down the stack call? Can anyone provide any insight on how to read these codes so I could interpret where I actually need to look.
Any information or guidance on reading the exception or making any use of it, and then trouble shooting it would be helpful. The test below is copied from windows log when the event was thrown.
Thanks in advance for any help.
Application: Epic.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.AccessViolationException [![enter image description here][1]][1]
at MemMap.ComBuf.IsCharAvailable(Int32)
at HMI.frmPmacStat.RefreshTimer_Elapsed(System.Object, System.Timers.ElapsedEventArgs)
at System.Timers.Timer.MyTimerCallback(System.Object)
at System.Threading.TimerQueueTimer.CallCallbackInContext(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.TimerQueueTimer.CallCallback()
at System.Threading.TimerQueueTimer.Fire()
at System.Threading.TimerQueue.FireQueuedTimerCompletion(System.Object)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
There are exceptions that are thrown by the c++ runtime environment, as a result of executing a throw expression, and there are other types of errors caused by the operating system or hardware trapping your instruction. Invalid access to memory is generally not thrown by code in c++, but is a side effect of evaluating an expression trying to access memory at an invalid address, resulting in the OS signaling the process, usually killing it. Because it's outside C++, it tends to be platform specific, but typical errors are:
reading a null pointer
using a pointer to an object that has been deleted
going outside an array's valid range of elements
using invalidated iterators into STL containers
Generally speaking, you can test for null and array bounds at runtime to detect the problem before it happens. Using a dangling pointer is more difficult to track down, because the time between the delete and the mis-use of that pointer can be long, and it can be difficult to find why it happened without a memory debugger, such as valgrind. Using smart pointers instead of raw pointers can help mitigate the problems of mis-managing memory, and can help avoid such errors.
Invalid iterators are subset of the general dangling pointer problem, but are common enough to be worth mentioning as their own category. Understanding your containers and which operations invalidate them is crucial, and some implementations can be compiled in "debug mode" which can help detect use of invalidated iterators.
As others have noted, this type of error is tricky to identify without digging into the code and running tests (automated or manual). The more pieces of the system you can pull out and still reproduce it, the better. Divide and conquer is your friend here.
Beyond that, it all depends how important it is for you to resolve this and how much effort you're willing to put in. There are at least three classes of tools that can help with such intermittent problems:
Application monitors that track potential errors as your application runs. These tend to slow your program significantly (10x or more slowdown). Examples include:
Microsoft's Application Verifier
Open-source and cross-platform Dr. Memory
Google's Crashpad. Unlike the previous two programs, this one requires instrumenting your code. It is also (allegedly -- haven't tried it) easier to use with helpers like Backtrace's commercial integration for analyzing Crashpad output
Google's Sanitizers - free and some are built into gcc and clang. There's also a Windows port of Address Sanitizer, but a cursory look suggests it may be a little bit of a second-class citizen.
If you can run and repro it also run it on Linux, you could use valgrind; rr (see this CppCast ep) which is a free extension for gdb that records and replays your program so you can record a debug session that crashed and then step through it to see what went wrong; and/or UndoDB and friends from Undo software, which is a more sophisticated, commercial product like rr.
Static analysis of the code. This is a set of tools that looks for common errors in your code. It generally has a low signal-to-noise ratio, so there are a lot of minor things to dig through if your run it on a large, existing project (best to start a project using these things from the beginning if possible). That said, many of the warnings are invaluable. Examples:
Most compilers have a subset of this functionality built in. If you're using Visual Studio, add /W4 /WX to your compilation flags for the C++ code to force maximum warnings, then fix all the warnings. For gcc and clang, add '-Wall -Wpedantic -Werror` to enforce no warnings.
PVS-Studio (commercial)
PC-Lint (commercial)
If you can instrument the code to write log messages, something like Debugview++ may be of assistance.
Things get harder if you have multithreading going on, which it looks like you do, because the non-determinism gets harder to track, there are new classes of possible errors that are introduced, and some of the above tools won't work well (e.g., I think rr is single-threaded only). Beyond a full IDE like Visual Studio, you'd need to go with something like Intel's Inspector (formerly Intel Thread Checker), or on Linux, Valgrind's Helgrind and DRD and ThreadSanitizer (in the sanitizers above, but also Linux only AFAIK). But hopefully this list gives you a place to start.
Since some days, I have been facing a problem in Visual Studio 2008, related to my C++ software.
If I set Visual Studio settings to "Release Win32" mode, it works fine.
But if I set it to "Debug Win32", it has crash problems when using delete. Compiling is alright, but, when running, the software crashes on 1st "delete" it meets.
Consider this snaphsot:
As you can see, when software arrives to "delete temp;" command execution, it crashes showing the message:
Debug Assertion Failed!
Program...
Expression _BLOCK_TYPE_IS_VALID(pHead->nBlockHouse)
What is the problem?
How to solve it?
Why in "Release" mode it doesn't have any errors?
Thanx
You should only delete what you new and delete[] what you new[]. Nothing else. You're also trying to use a null pointer to call a function. What happens when you try to call a method of nothing? Well, it can't be anything good.
You have temp = NULL and on the next line you call a method on it? And then you try do delete it?
In addition to that assertions aren't "errors". Assertions are there in debug mode to declare that you are asserting a certain condition (these often are also included throughout libraries such as the MFC) and if your assertion fails it calls code to inform you about it and give you the chance to break into the debugger in order to debug the issue.
The debugger does an "assertion". This is an additional check for correctness of the code like eg: "assert that the pointer is not null.". It's good that it is doing so, because it helps finding errors. I agree to anybody who claims that the message emitted by the debugger does not help finding the source for the error.
We have an application that is a C/C++/MFC desktop application, with some C++/CLI assemblies that allow us to access some managed code functionality. The app is crashing at startup in release mode only with the message
An unhandled exception of type 'System.TypeInitializationException' occurred in Unknown Module.
Additional information: The type initializer for '' threw an exception.
How can I go about debugging this scenario and what are the issues in mixing managed/unmanaged code? What special steps do I have to take to make them play nicely?
Things to suspect are:
Missing unmanaged DLLs. You can use Depends (from Sysinternals) and start profiling, but I've struggled to get good results in mixed-mode.
Make a native minimal test harness which has the same dependencies, and run that through Depends - you will get definitive information about missing DLLs.
Are you using obfuscation in your release build product?
The obfuscation software we use adds a field to types in evaluation mode. We have fixed offset structs, yet the new field doesn't get an explicit offset. This is an error which would be flagged up at compile time if it was in our own code. Since the obfuscator is dynamically patching the assembly, the CLR has no option but to fail to load the invalid type at runtime.
In my opinion (based on some trouble I have had) Matt Smith's comment is the most useful answer; actually, check 'Thrown' for all types of exception. Quite often the problem is a crash in the constructor of a global object. See also answer 5 at
http://www.codeproject.com/Questions/67419/The-type-initializer-for-threw-an-exception
which says (among other things):
Click Debug--> Exceptions and check ON all the Thrown checkboxes. This
will cause the debugger to stop on all first chance exceptions and
will help you find the error under the Type Initializer error that
you're seeing. If it is related to another assembly, as mine was, you
can use Microsoft's Assembly Binding Log Viewer tool to help determine
the problem.
I've seen posts talk about what might cause differences between Debug and Release builds, but I don't think anybody has addressed from a development standpoint what is the most efficient way to solve the problem.
The first thing I do when a bug appears in the Release build but not in Debug is I run my program through valgrind in hopes of a better analysis. If that reveals nothing, -- and this has happened to me before -- then I try various inputs in hopes of getting the bug to surface also in the Debug build. If that fails, then I would try to track changes to find the most recent version for which the two builds diverge in behavior. And finally I guess I would resort to print statements.
Are there any best software engineering practices for efficiently debugging when the Debug and Release builds differ? Also, what tools are there that operate at a more fundamental level than valgrind to help debug these cases?
EDIT: I notice a lot of responses suggesting some general good practices such as unit testing and regression testing, which I agree are great for finding any bug. However, is there something specifically tailored to this Release vs. Debug problem? For example, is there such a thing as a static analysis tool that says "Hey, this macro or this code or this programming practice is dangerous because it has the potential to cause differences between your Debug/Release builds?"
One other "Best Practice", or rather a combination of two: Have Automated Unit Tests, and Divide and Conquer.
If you have a modular application, and each module has good unit tests, then you may be able to quickly isolate the errant piece.
The very existence of two configurations is a problem from debugging point of view. Proper engineering would be such that the system on the ground and in the air behave the same way, and achieve this by reducing the number of ways by which the system can tell the difference.
Debug and Release builds differ in 3 aspects:
_DEBUG define
optimizations
different version of the standard library
The best way around, the way I often work, is this:
Disable optimizations where performance is not critical. Debugging is more important. Most important is disable function auto-inlining, keep standard stack frame and variable reuse optimizations. These annoy debug the most.
Monitor code for dependence on DEBUG define. Never use debug-only asserts, or any other tools sensitive to DEBUG define.
By default, compile and work /release.
When I come across a bug that only happens in release, the first thing I always look for is use of an uninitialized stack variable in the code that I am working on. On Windows, the debug C runtime will automatically initialise stack variables to a know bit pattern, 0xcdcdcdcd or something. In release, stack variables will contain the value that was last stored at that memory location, which is going to be an unexpected value.
Secondly, I will try to identify what is different between debug and release builds. I look at the compiler optimization settings that the compiler is passed in Debug and Release configurations. You can see this is the last property page of the compiler settings in Visual Studio. I will start with the release config, and change the command line arguments passed to the compiler one item at a time until they match the command line that is used for compiling in debug. After each change I run the program and reproducing the bug. This will often lead me to the particular setting that causes the bug to happen.
A third technique can be to take a function that is misbehaving and disable optimizations around it using the pre-processor. This will allow you run the program in release with the particular function compiled in debug. The behaviour of the program which has been built in this way will help you learn more about the bug.
#pragma optimize( "", off )
void foo() {
return 1;
}
#pragma optimize( "", on )
From experience, the problems are usually stack initialization, memory scrubbing in the memory allocator, or strange #define directives causing the code to be compiled incorrectly.
The most obvious cause is simply the use of #ifdef and #ifndef directives associated DEBUG or similar symbol that change between the two builds.
Before going down the debugging road (which is not my personal idea of fun), I would inspect both command lines and check which flags are passed in one mode and not the other, then grep my code for this flags and check their uses.
One particular issue that comes to mind are macros:
#ifdef _DEBUG_
#define CHECK(CheckSymbol) { if (!(CheckSymbol)) throw CheckException(); }
#else
#define CHECK(CheckSymbol)
#endif
also known as a soft-assert.
Well, if you call it with a function that has side effect, or rely on it to guard a function (contract enforcement) and somehow catches the exception it throws in debug and ignore it... you will see differences in release :)
When debug and release differ it means:
you code depends on the _DEBUG or similar macros (defined when compiling a debug version - no optimizations)
your compiler has an optimization bug (I seen this few times)
You can easily deal with (1) (code modification) but with (2) you will have to isolate the compiler bug. After isolating the bug you do a little "code rewriting" to get the compiler generate correct binary code (I did this a few times - the most difficult part is to isolate the bug).
I can say that when enabling debug information for release version the debugging process works ... (though because of optimizations you might see some "strange" jumps when running).
You will need to have some "black-box" tests for your application - valgrind is a solution in this case. These solutions help you find differences between release and debug (which is very important).
The best solution is to set up something like automated unit testing to thoroughly test all aspects of the application (not just individual components, but real world tests which use the application the same way a regular user would with all of the dependencies). This allows you to know immediately when a release-only bug has been introduced which should give you a good idea of where the problem is.
Good practice to actively monitor and seek out problems beats any tool to help you fix them long after they happen.
However, when you have one of those cases where it's too late: too many builds have gone by, can't reproduce consistently, etc. then I don't know of any one tool for the job. Sometimes fiddling with your release settings can give a bit of insight as to why the bug is occurring: if you can eliminate optimizations which suddenly make the bug go away, that could give you some useful information about it.
Release-only bugs can fall into various categories, but the most common ones (aside from something like a misuse of assertions) is:
1) Uninitialized memory. I use this term over uninitialized variables as a variable may be initialized but still be pointing to memory which hasn't been initialized properly. For this, memory diagnostic tools like Valgrind can help.
2) Timing (ex: race conditions). These can be a nightmare to debug, but there are some multithreading profilers and diagnostic tools which can help. I can't suggest any off the bat, but there's Coverity Integrity Manager as one example.
I've recently implemented some vectored exception handling to catch errors in our software. This is especially useful as we've just converted from vc6 to vs2005. We're encountering a few problems with the use of the STL library (generally people doing things they shouldn't). I'm trying to catch these errors with my vectored exception handler.
However this doesn't seem to get called, instead these errors are internally processed by the Microsoft Visual Studio C Runtime library.
My question is;
Is there a way to turn off the runtime error checking and get the exceptions passed to the VE handler?
Thanks
Rich
http://msdn.microsoft.com/en-us/library/aa985973%28VS.80%29.aspx
#define _SECURE_SCL 1
#define _SECURE_SCL_THROWS 1
The above allows me to throw exceptions.
You can turn off the additional run-time checks. However, not all errors this catches will result in a crash which you can intercept.
On a sidenote: These checks often consume significant performance and are, by default, not turned off in release builds.
#define _SECURE_SCL 0
It's best to do this via project settings, as you could get nasty linker problems if the setting differs within or between files.
I ran into this problem a while ago and it took me some time to wrap my head around what they are doing in their runtime. I would recommend reading "Migrating from Previous Versions of Visual C++" on MSDN at least twice. Then read "Extensions to the C Library, Part I: Bounds-checking interfaces (ISO/IEC TR 24731-1)". The latter is the standard that most of the parameter checking stuff is based on.
Once you understand what they are up to, just define _CRT_SECURE_NO_DEPRECATE, _SECURE_SCL, and _SECURE_SCL_THROWS in your project settings. Then make sure that you have "Enable C++ Exceptions" set to "Yes with SEH Exceptions (/EHa)" and "Basic Runtime Checks" set to "Default" in your project. At least, that is what is working for us right now. It did take some time to remove the incorrect code that we had created under VC6 though.
The most important thing that you can do is set aside a few weeks and really dig into what the various options and macros do. Then figure out what works with your code. We didn't do this early enough and it hurt a lot once we had some "bad builds" make it out of engineering.