108

I've got a "Schroedinger's Cat" type of problem here -- my program (actually the test suite for my program, but a program nonetheless) is crashing, but only when built in release mode, and only when launched from the command line. Through caveman debugging (ie, nasty printf() messages all over the place), I have determined the test method where the code is crashing, though unfortunately the actual crash seems to happen in some destructor, since the last trace messages I see are in other destructors which execute cleanly.

When I attempt to run this program inside of Visual Studio, it doesn't crash. Same goes when launching from WinDbg.exe. The crash only occurs when launching from the command line. This is happening under Windows Vista, btw, and unfortunately I don't have access to an XP machine right now to test on.

It would be really nice if I could get Windows to print out a stack trace, or something other than simply terminating the program as if it had exited cleanly. Does anyone have any advice as to how I could get some more meaningful information here and hopefully fix this bug?

Edit: The problem was indeed caused by an out-of-bounds array, which I describe more in this post. Thanks everybody for your help in finding this problem!

Community
  • 1
  • 1
Nik Reiman
  • 39,067
  • 29
  • 104
  • 160
  • Can you give a sample of that test method? – akalenuk Oct 09 '08 at 08:31
  • No sorry, the code is much too complex to easily paste in here, and as I mentioned, it isn't happening in the test method itself, but rather a destructor afterwards. There are no uninitialized pointers or anything like that in this method, though. – Nik Reiman Oct 09 '08 at 10:24
  • 3
    Most answers are little more than guesses. There are a few common techniques to analyze crashing release builds without attaching a debugger: http://stackoverflow.com/a/18513077/214777?stw=2 – Sebastian Aug 29 '13 at 14:04
  • Maybe it's not your fault: [Is optimisation level -O3 dangerous in g++?](http://stackoverflow.com/q/11546075/86967) – Brent Bradburn Apr 15 '17 at 18:21

29 Answers29

152

In 100% of the cases I've seen or heard of, where a C or C++ program runs fine in the debugger but fails when run outside, the cause has been writing past the end of a function local array. (The debugger puts more on the stack, so you're less likely to overwrite something important.)

James Curran
  • 101,701
  • 37
  • 181
  • 258
  • 36
    Somebody give this man a cigar! In my case, I was passing in a StringBuilder that didn't have a big enough capacity to a P/Invoke function. I guess it's like someone writing on your face with a magic marker when you're asleep: under the debugger, they end up scribbling on your forehead, so you don't notice, but without the debugger, they end up stabbing you in the eye ... something like that. Thanks for this tip! – Nicholas Piasecki Aug 20 '09 at 13:58
  • 1
    In my case it turned out to be an alignment issue on an ARM processor using Obj-C. – Almo May 16 '13 at 12:16
  • I had one once caused by CArray doing bitwise copies instead of copy assignment. But all other release crashes I've heard of were writing past the end of the array. – Mooing Duck Aug 29 '13 at 17:57
  • Another 1 out of 1 from me to add to this being the bug. – Wuschelbeutel Kartoffelhuhn Oct 07 '17 at 08:56
  • 1
    11 years later and this still rings true... don't forget to reserve your vectors. – dav May 19 '19 at 04:47
  • 1
    ok, so then how does one change the behaviour of debug mode so that one can actually debug. – Paul Childs Jul 16 '19 at 23:45
  • @PaulChilds You cannot change the behavior--- It's needed for the debugger to debug. But, now knowing where to look, you should be able to find & fix the problem without the debugger. – James Curran Jul 18 '19 at 19:57
  • 1
    "Now knowing where to look" but how does everything working in debug tell you *where* the problem is. Although I think your answer is correct in most instances, and knowing what to look for is a good start, trolling through a large codebase to pinpoint exactly where the problem is can be prohibitively expensive. – Paul Childs Jul 20 '19 at 00:12
  • In my case it turned out to be caused by `to_string(a/b)`, where b is an integer of value 0. It would never segfault for debug mode, but for release mode that code would sometimes work and sometimes fail (depending on where in the program it was). Dividing by an integer with value 0 is undefined behavior, so I think that's why it works in debug mode but sometimes not in release mode. – MindSeeker Aug 12 '20 at 19:00
  • God Walking Amongst Mere Mortals – user2997204 Apr 23 '21 at 15:53
  • Yeah on Android NDK It was running into array and vector locations out of index! Thanks! – Danoli3 Aug 31 '21 at 05:28
59

When I have encountered problems like this before it has generally been due to variable initialization. In debug mode, variables and pointers get initialized to zero automatically but in release mode they do not. Therefore, if you have code like this

int* p;
....
if (p == 0) { // do stuff }

In debug mode the code in the if is not executed but in release mode p contains an undefined value, which is unlikely to be 0, so the code is executed often causing a crash.

I would check your code for uninitialized variables. This can also apply to the contents of arrays.

David Dibben
  • 18,460
  • 6
  • 41
  • 41
  • Typical cases are forgetting to put a member variable in (one of) the constructors member initializing list. Has the same effect but it's harder to find if you don't know that you should look for proper member initialization as well. – steffenj Oct 09 '08 at 07:56
  • 1
    In debug mode the variables are usually initialized to some 'Compiler Defined constant' that can be used in debugging to indicate what state the variable is in. For Example: pointers NULL or 0xDeadBeef is popular. – Martin York Oct 09 '08 at 15:38
  • Debug runtimes typically initialize memory to some nonzero value, specifically so that NULL pointer tests will cause the code to act as if the pointer we're non-NULL. Otherwise you have code that runs correctly in debug mode that crashes release mode. – Michael Burr Oct 09 '08 at 17:23
  • 1
    No, the variables are not initialised at all and it's still UB to "use" them until they're assigned-to. However, the underlying memory contents are often prefilled with 0x0000000 or 0xDEADBEEF or other recognisable patterns. – Lightness Races in Orbit Apr 05 '11 at 11:45
32

No answer so far has tried to give a serious overview about the available techniques for debugging release applications:

  1. Release and Debug builds behave differently for many reasons. Here is an excellent overview. Each of these differences might cause a bug in the Release build that doesn't exist in the Debug build.

  2. The presence of a debugger may change the behavior of a program too, both for release and debug builds. See this answer. In short, at least the Visual Studio Debugger uses the Debug Heap automatically when attached to a program. You can turn the debug heap off by using environment variable _NO_DEBUG_HEAP . You can specify this either in your computer properties, or in the Project Settings in Visual Studio. That might make the crash reproducible with the debugger attached.

    More on debugging heap corruption here.

  3. If the previous solution doesn't work, you need to catch the unhandled exception and attach a post-mortem debugger the instance the crash occurs. You can use e.g. WinDbg for this, details about the avaiable post-mortem debuggers and their installation at MSDN

  4. You can improve your exception handling code and if this is a production application, you should:

    a. Install a custom termination handler using std::set_terminate

    If you want to debug this problem locally, you could run an endless loop inside the termination handler and output some text to the console to notify you that std::terminate has been called. Then attach the debugger and check the call stack. Or you print the stack trace as described in this answer.

    In a production application you might want to send an error report back home, ideally together with a small memory dump that allows you to analyze the problem as described here.

    b. Use Microsoft's structured exception handling mechanism that allows you to catch both hardware and software exceptions. See MSDN. You could guard parts of your code using SEH and use the same approach as in a) to debug the problem. SEH gives more information about the exception that occurred that you could use when sending an error report from a production app.

Community
  • 1
  • 1
Sebastian
  • 4,802
  • 23
  • 48
16

Things to look out for:

Array overruns - the visual studio debugger inserts padding which may stop crashes.

Race conditions - do you have multiple threads involved if so a race condition many only show up when an application is executed directly.

Linking - is your release build pulling in the correct libraries.

Things to try:

Minidump - really easy to use (just look it up in msdn) will give you a full crash dump for each thread. You just load the output into visual studio and it is as if you were debugging at the time of the crash.

morechilli
  • 9,827
  • 7
  • 33
  • 54
13

You can set WinDbg as your postmortem debugger. This will launch the debugger and attach it to the process when the crash occurs. To install WinDbg for postmortem debugging, use the /I option (note it is capitalized):

windbg /I

More details here.

As to the cause, it's most probably an unitialized variable as the other answers suggest.

Franci Penov
  • 74,861
  • 18
  • 132
  • 169
11

After many hours of debugging, I finally found the cause of the problem, which was indeed caused by a buffer overflow, caused a single byte difference:

char *end = static_cast<char*>(attr->data) + attr->dataSize;

This is a fencepost error (off-by-one error) and was fixed by:

char *end = static_cast<char*>(attr->data) + attr->dataSize - 1;

The weird thing was, I put several calls to _CrtCheckMemory() around various parts of my code, and they always returned 1. I was able to find the source of the problem by placing "return false;" calls in the test case, and then eventually determining through trial-and-error where the fault was.

Thanks everybody for your comments -- I learned a lot about windbg.exe today! :)

Nik Reiman
  • 39,067
  • 29
  • 104
  • 160
  • 10
    Today I've been debugging a similar problem and _CrtCheckMemory() was always returning 1. But then I realized why: in Release mode, _CrtCheckMemory is #defined's as ((int)1). – Brian Morearty Feb 16 '11 at 19:28
7

Even though you have built your exe as a release one, you can still generate PDB (Program database) files that will allow you to stack trace, and do a limited amount of variable inspection. In your build settings there is an option to create the PDB files. Turn this on and relink. Then try running from the IDE first to see if you get the crash. If so, then great - you're all set to look at things. If not, then when running from the command line you can do one of two things:

  1. Run EXE, and before the crash do an Attach To Process (Tools menu on Visual Studio).
  2. After the crash, select the option to launch debugger.

When asked to point to PDB files, browse to find them. If the PDB's were put in the same output folder as your EXE or DLL's they will probably be picked up automatically.

The PDB's provide a link to the source with enough symbol information to make it possible to see stack traces, variables etc. You can inspect the values as normal, but do be aware that you can get false readings as the optimisation pass may mean things only appear in registers, or things happen in a different order than you expect.

NB: I'm assuming a Windows/Visual Studio environment here.

Greg Whitfield
  • 5,649
  • 2
  • 30
  • 32
4

Crashes like this are almost always caused because an IDE will usually set the contents of uninitialized variable to zeros, null or some other such 'sensible' value, whereas when running natively you'll get whatever random rubbish that the system picks up.

Your error is therefore almost certainly that you are using something like you are using a pointer before it has been properly initialized and you're getting away with it in the IDE because it doesn't point anywhere dangerous - or the value is handled by your error checking - but in release mode it does something nasty.

Cruachan
  • 15,733
  • 5
  • 59
  • 112
3

In order to have a crash dump that you can analyze:

  1. Generate pdb files for your code.
  2. You rebase to have your exe and dlls loaded in the same address.
  3. Enable post mortem debugger such as Dr. Watson
  4. Check the crash failures address using a tool such as crash finder.

You should also check out the tools in Debugging tools for windows. You can monitor the application and see all the first chance exceptions that were prior to your second chance exception.

Hope it helps...

Yuval Peled
  • 4,988
  • 8
  • 30
  • 36
3

Sometimes this happens because you have wrapped important operation inside "assert" macro. As you may know, "assert" evaluates expressions only on debug mode.

  • Yes, this one got me. I was able to use VSCode with a search regex of assert\(.*\( to track this down. – Matt Nov 13 '22 at 01:01
3

A great way to debug an error like this is to enable optimizations for your debug build.

Mgill404
  • 115
  • 1
  • 9
2

Once i had a problem when app behaved similarily to yours. It turned out to be a nasty buffer overrun in sprintf. Naturally, it worked when run with a debugger attached. What i did, was to install an unhandled exception filter (SetUnhandledExceptionFilter) in which i simply blocked infinitely (using WaitForSingleObject on a bogus handle with a timeout value of INFINITE).

So you could something along the lines of:

long __stdcall MyFilter(EXCEPTION_POINTERS *)
{
    HANDLE hEvt=::CreateEventW(0,1,0,0);
    if(hEvt)
    {
        if(WAIT_FAILED==::WaitForSingleObject(hEvt, INFINITE))
        {
            //log failure
        }
    }

}
// somewhere in your wmain/WinMain:
SetUnhandledExceptionFilter(MyFilter);

I then attached the debugger after the bug had manifested itself (gui program stopped responding).

Then you can either take a dump and work with it later:

.dump /ma path_to_dump_file

Or debug it right away. The simplest way is to track where processor context has been saved by the runtime exception handling machinery:

s-d esp Range 1003f

Command will search stack address space for CONTEXT record(s) provided the length of search. I usually use something like 'l?10000'. Note, do not use unsually large numbers as the record you're after usually near to the unhanded exception filter frame. 1003f is the combination of flags (i believe it corresponds to CONTEXT_FULL) used to capture the processor state. Your search would look similar to this:

0:000> s-d esp l1000 1003f
0012c160 0001003f 00000000 00000000 00000000 ?...............

Once you get results back, use the address in the cxr command:

.cxr 0012c160

This will take you to this new CONTEXT, exactly at the time of crash (you will get exactly the stack trace at the time your app crashed). Additionally, use:

.exr -1

to find out exactly which exception had occurred.

Hope it helps.

deemok
  • 2,735
  • 19
  • 11
1

Vista SP1 actually has a really nice crash dump generator built into the system. Unfortunately, it isn't turned on by default!

See this article: http://msdn.microsoft.com/en-us/library/bb787181(VS.85).aspx

The benefit of this approach is that no extra software needs to be installed on the affected system. Grip it and rip it, baby!

1

With regard to your problems getting diagnostic information, have you tried using adplus.vbs as an alternative to WinDbg.exe? To attach to a running process, use

adplus.vbs -crash -p <process_id>

Or to start the application in the event that the crash happens quickly:

adplus.vbs -crash -sc your_app.exe

Full info on adplus.vbs can be found at: http://support.microsoft.com/kb/286350

DocMax
  • 12,094
  • 7
  • 44
  • 44
1

Ntdll.dll with debugger attached

One little know difference between launching a program from the IDE or WinDbg as opposed to launching it from command line / desktop is that when launching with a debugger attached (i.e. IDE or WinDbg) ntdll.dll uses a different heap implementation which performs some little validation on the memory allocation/freeing.

You may read some relevant information in unexpected user breakpoint in ntdll.dll. One tool which might be able to help you identifying the problem is PageHeap.exe.

Crash analysis

You did not write what is the "crash" you are experiencing. Once the program crashes and offers you to send the error information to the Microsoft, you should be able to click on the technical information and to check at least the exception code, and with some effort you can even perform post-mortem analysis (see Heisenbug: WinApi program crashes on some computers) for instructions)

Community
  • 1
  • 1
Suma
  • 33,181
  • 16
  • 123
  • 191
1

As my experience, that are most being memory corruption issues.

For example :

char a[8];
memset(&a[0], 0, 16);

: /*use array a doing some thing */

it is very possible to be normal in debug mode when one runs the code.

But in release, that would/might be crash.

For me, to rummage where the memory is out of bound is too toilsome.

Use some tools like Visual Leak Detector (windows) or valgrind (linux) are more wise choise.

Gaiger Chen
  • 301
  • 3
  • 18
1

I've seen a lot of right answers. However, there is none that helped me. In my case, there was a wrong usage of the SSE instructions with the unaligned memory. Take a look at your math library (if you use one), and try to disable SIMD support, recompile and reproduce the crash.

Example:

A project includes mathfu, and uses the classes with STL vector: std::vector< mathfu::vec2 >. Such usage will probably cause a crash at the time of the construction of mathfu::vec2 item since the STL default allocator does not guarantee required 16-byte alignment. In this case to prove the idea, one can define #define MATHFU_COMPILE_WITHOUT_SIMD_SUPPORT 1 before each include of the mathfu, recompile in Release configuration and check again.

The Debug and RelWithDebInfo configurations worked well for my project, but not the Release one. The reason behind this behavior is probably because debugger processes allocation/deallocation requests and does some memory bookkeeping to check and verify the accesses to the memory.

I experienced the situation in Visual Studio 2015 and 2017 environments.

Vlad Serhiienko
  • 103
  • 1
  • 9
0

Something similar happend to me once with GCC. It turned out to be a too aggressive optimization that was enabled only when creating the final release and not during the development process.

Well, to tell the truth it was my fault, not gcc's, as I didn't noticed that my code was relying on the fact that that particular optimization wouldn't have been done.

It took me a lot of time to trace it and I only came to it because I asked on a newsgroup and somebody made me think about it. So, let me return the favour just in case this is happening to you as well.

Remo.D
  • 16,122
  • 6
  • 43
  • 74
0

I've found this this article useful for your scenario. ISTR the compiler options were a little out of date. Look around your Visual Studio project options to see how to generate pdb files for your release build, etc.

fizzer
  • 13,551
  • 9
  • 39
  • 61
0

It's suspicious that it would happen outside the debugger and not inside; running in the debugger does not normally change the application behavior. I would check the environment differences between the console and the IDE. Also, obviously, compile release without optimizations and with debug information, and see if that affects the behavior. Finally, check out the post-mortem debugging tools other people have suggested here, usually you can get some clue from them.

Nick
  • 6,808
  • 1
  • 22
  • 34
0

Debugging release builds can be a pain due to optimizations changing the order in which lines of your code appear to be executed. It can really get confusing!

One technique to at least narrow down the problem is to use MessageBox() to display quick statements stating what part of the program your code has got to ("Starting Foo()", "Starting Foo2()"); start putting them at the top of functions in the area of your code that you suspect (what were you doing at the time when it crashed?). When you can tell which function, change the message boxes to blocks of code or even individual lines within that function until you narrow it down to a few lines. Then you can start printing out the value of variables to see what state they are in at the point of crashing.

0

Try using _CrtCheckMemory() to see what state the allocated memory is in . If everything goes well , _CrtCheckMemory returns TRUE , else FALSE .

Vhaerun
  • 12,806
  • 16
  • 39
  • 38
0

You might run your software with Global Flags enabled (Look in Debugging Tools for Windows). It will very often help to nail the problem.

Marcin Gil
  • 68,043
  • 8
  • 59
  • 60
0

Make your program generate a mini dump when the exception occurs, then open it up in a debugger (for example, in WinDbg). The key functions to look at: MiniDumpWriteDump, SetUnhandledExceptionFilter

mikhailitsky
  • 67
  • 2
  • 7
0

Here's a case I had that somebody might find instructive. It only crashed in release in Qt Creator - not in debug. I was using .ini files (as I prefer apps that can be copied to other drives, vs. ones that lose their settings if the Registry gets corrupted). This applies to any apps that store their settings under the apps' directory tree. If the debug and release builds are under different directories, you can have a setting that's different between them, too. I had preference checked in one that wasn't checked in the other. It turned out to be the source of my crash. Good thing I found it.

I hate to say it, but I only diagnosed the crash in MS Visual Studio Community Edition; after having VS installed, letting my app crash in Qt Creator, and choosing to open it in Visual Studio's debugger. While my Qt app had no symbol info, it turns out that the Qt libraries had some. It led me to the offending line; since I could see what method was being called. (Still, I think Qt is a convenient, powerful, & cross-platform LGPL framework.)

CodeLurker
  • 1,248
  • 13
  • 22
0

I had this problem too. In my case, the RELEASE mode was having msvscrtd.dll in the linker definition. We removed it and the issue resolved.

Alternatively, adding /NODEFAULTLIB to the linker command line arguments also resolved the issue.

Pavan Dittakavi
  • 3,013
  • 5
  • 27
  • 47
0

I'll add another possibility for future readers: Check if you're logging to stderr or stdout from an application with no console window (ie you linked with /SUBSYSTEM:WINDOWS). This can crash.

I had a GUI application where I logged to both stderr and a file in both debug and release, so logging was always enabled. I created a console window in debug for easy viewing of the logs, but not in release. However, if the VS debugger is attached to the release build, it'll automatically pipe stderr to the VS output window. So only in release with no debugger did it actually crash when I wrote to stderr.

To make things worse, printf debugging obviously didn't work, which I didn't understand why until I'd tracked down the root cause (by painfully bisecting the codebase by inserting an infinite loop in various spots).

Lewis
  • 1,310
  • 1
  • 15
  • 28
-3

I had this error and vs crashed even when trying to !clean! my project. So I deleted the obj files manually from the Release directory, and after that it built just fine.

-6

I agree with Rolf. Because reproducibility is so important, you shouldn't have a non-debug mode. All your builds should be debuggable. Having two targets to debug more than doubles your debugging load. Just ship the "debug mode" version, unless it is unusable. In which case, make it usable.

wnoise
  • 9,764
  • 37
  • 47
  • This may work for 10% of applications but certainly not for all of them. Would you want to play games released as DEBUG builds? Give away your trademarked secret security code in disassembly-friendly mode, maybe even along with the PDBs? I guess not. – steffenj Oct 09 '08 at 08:01
  • Steffenj: I want game developers to find bugs. Ideally, before they ship, but if it's after, I want them to be able to get enough information to reproduce and track it down. if it's secret code, trademark doesn't apply. PDBs? Protein data-bank? python debugger? – wnoise Oct 09 '08 at 22:36
  • IMHO, that's a bad idea. The executables are larger, they are not optimized, and run a lot slower. These cases are really pretty rare; even though especially maddening when they do happen. You shouldn't deliver consistently inferior product, worrying about extremely rare worst-case debugging. (Mine was not one of the many downvotes.) I did some programming for NASA; and we said that at a bare minimum, every line of code should be tested once. Unit testing can also help. – CodeLurker Oct 05 '18 at 00:01