Debug is normal, and the reason for release failure

Source: Internet
Author: User
Tags assert volatile

Discussion on the essential difference between debug and release
first, Debug and release

The essential difference between compiling methods debug is often referred to as a debug version, which contains debugging information and is not optimized for programmers to debug programs. Release is known as a publish version, it is often a variety of optimizations, so that the code size and speed of the program is optimal, so that users are very good to use. The real secret of Debug and release is a set of compilation options. The following lists the options for both (there are, of course, other things, such as/FD/FO, but the difference is not important, and usually they don't cause release errors, not discussed here)


Debug version:/MD

D/MLD or/MTD using the Debug Runtime Library (debug version of the Run-time function library)/od turn off the tuning switch/d "_DEBUG" equivalent to #define _DEBUG, open the Compile debug code switch (mainly for the Assert function)/ ZI Create an Edit and continue (edit continue) database, so that if you modify the source code without recompiling/gz during debugging, you can help catch memory errors/gm turn on minimizing the link switch and reduce the link time


Release version:/MD/ML or/MT Use the release version of the runtime function library/o1 or/o2 optimization switch to make the program minimum or fastest/d "ndebug" off condition compile debug code switch (that is, do not compile assert function)/g F Merge duplicate strings, and the character String constants are placed in read-only memory to prevent modification in fact, Debug and release have no intrinsic boundaries, they are just a collection of compilation options, and the compiler only acts according to the predefined options.  In fact, we can even modify these options to get optimized debug versions or release versions with trace statements. second, in which case release version will be wrong


1. Runtime Library: Link which run-time function library usually only has an impact on the performance of the program. The debug version of the Runtime Library contains debugging information and has some protection mechanisms to help identify errors, so performance is not as good as the release version. The Runtime Library provided by the compiler is usually stable and does not cause release errors; but because the debug Runtime library has tightened detection of bugs, such as heap memory allocations, there are times when debug errors but releases are normal. It should be noted that, if Debug error, even if the release is normal, the program must be a Bug, but may be released version of a run did not show it.


2. Optimization: This is the primary cause of the error, because the source program is basically translated directly when the optimization is turned off, and the compiler makes a series of assumptions when the optimization is turned on. Such errors are mainly as follows: (1) frame pointer (pointer) ellipsis (FPO): In the function call process, all call information (return address, parameters) and automatic variables are placed on the stack. If the declaration of the function is different from the implementation (parameter, returns the value, the invocation method), will produce the error ———— but in the Debug way, the stack's access is realized through the EBP register save address, if does not have the array to cross the line and so on error (or crosses the line "not many"), the function usually can execute normally; release mode, optimizations omit the EBP stack base address pointer, so accessing the stack via a global pointer causes the return address error to be a program crash. The strongly typed nature of C + + can check out most of these errors, but not if you use coercion type conversions. You can force the/oy-compilation option in release version to turn off frame pointer ellipsis to determine whether this type of error occurs. This type of error is usually:

MFC Message response function write error. The correct should be afx_msg lresult Onmessageown (WPARAM WPARAM, LPARAM LPARAM); On_message macros contain coercion type conversions. One way to prevent this error is to redefine the On_message macro and add the following code to the stdafx.h (after #include "AFXWIN.h"), the compiler will complain when the function is in the wrong shape

#undef on_message #define ON_MESSAGE (message, MEMBERFXN) \ {message, 0, 0, 0, AFXSIG_LWL, \ (afx_pmsg) (AFX_PMSGW) (Static _cast< lresult (afx_msg_call \ CWnd::*) (WPARAM, LPARAM) > (&MEMBERFXN)},


(2) Volatile variable: volatile tells the compiler that the variable may be modified in an unknown way outside of the program (such as system, other processes, and threads). In order to improve program performance, the optimizer often places variables in registers (similar to the Register keyword), while other processes can only modify the memory in which the variable resides, while the value in the register does not change. If your program is multi-threaded, or you find that the value of a variable does not match what you expected and you are sure you have set it correctly, you are likely to experience this problem. This type of error can sometimes be manifested as a program with the fastest optimization error and minimal optimization normal. Try to add volatile to the variable you think is suspicious.


(3) Variable optimization: The optimizer optimizes variables based on the use of variables. For example, there is an unused variable in the function that in the Debug version might mask an array out of bounds, and in release, the variable is likely to be tuned, and the array's bounds will break the useful data in the stack. Of course, the actual situation would be much more complicated than that. The errors associated with this are:

Illegal access, including array bounds, pointer errors, and so on. For example void fn (void) {int i; i = 1; int a[4]; {int J; j = 1;} A[-1] = 1;//of course

Errors are not so obvious, such as subscript is variable a[4] = 1; Although the scope was out when the array was out of bounds,

But the space is not retracted, so I and J will cover the boundaries. And the release version because I, J does not have a big role

may be optimized, causing the stack to be corrupted.



3. _debug  and  ndebug : When  _DEBUG  is defined, the ASSERT ()   function is compiled, and  NDEBUG  is not compiled. In addition, VC + + also has a series of assertion macros. This includes: ansi c  assertion  void assert (int expression );  c runtime lib   Assertion  _assert ( booleanExpression );  _asserte ( booleanExpression );  mfc   Assertion  assert ( booleanExpression );  verify ( booleanExpression );

Assert_valid (Pobject); Assert_kindof (classname, pobject); ATL Assertion Atlassert (booleanexpression); In addition, the compilation of TRACE () macros is also controlled by _DEBUG. All of these assertions are compiled only in the debug edition and are ignored in release editions. The only exception is VERIFY (). In fact, all of these macros invoke the Assert () function, except that some debugging code related to the library is attached. If you add any program code to these macros, not just Boolean expressions (such as assignment, function calls that can change the value of variables, etc.), then the release version does not perform these operations, causing errors. Beginners are very easy to make such errors, the search method is also very simple, because these macros are listed above, as long as the use of VC + + found in the files in all the documents to find a place to use these macros to check again. In addition, some experts may also join #ifdef _DEBUG and other conditions such as compiling, but also pay attention to. Incidentally, it's worth mentioning the VERIFY () macro, which allows you to put program code in a Boolean expression
In This macro is typically used to check the return value of the Windows API. Some people may abuse VERIFY for this reason.
(), in fact this is dangerous, because VERIFY () violates the assertion of the idea that the program code and debugging code

A complete separation may eventually lead to a lot of trouble. Therefore, experts recommend that you use this macro as little as possible.



4./GZ option: This option will do the following

(1) Initialize memory and variables. This includes the 0xCC initialization of all automatic variables, the allocated memory in the 0xCD (cleared data) initialization heap (that is, dynamically allocated memory, such as new), and 0xD D (Dead data) to populate the heap memory that has been freed (for example, delete), 0xFD (DE FENCDE Data) Early
To start a protected memory (the debug version adds protected memory before and after dynamically allocating memory to prevent cross-border access), its
The words in brackets are Microsoft's suggested mnemonics. The advantage of this is that these values are very large and as pointers are not possible
(and pointers in 32-bit systems are rarely odd numbers, and in some systems odd pointers can produce run-time errors),
Are rarely encountered as numeric values and are easily recognizable, so it is advantageous to find the Re in the Debug edition
Lease version of the error encountered. The special note is that many people think that the compiler will initialize variables with 0来, which

Is wrong (and this is bad for finding errors).


(2) when calling a function through a function pointer, it passes through the check stack

The pointer verifies the match of a function call. (prevent the prototype from being mismatched)


(3) Check the stack pointer before returning the function to confirm that it has not been modified. (Prevent Cross-border access and prototype mismatch, together with the second item can be roughly simulated frame pointer omitted FPO)
Usually the/GZ option causes the Debug version to go wrong and the release version is normal because the release version is not in the beginning
The initialization variable is random, which may cause the pointer to point to a valid address and hide the illegal access. Besides

/GM/GF and other options cause fewer errors, and their effects are obvious and relatively easy to spot.


Third, how to "Debug" release version of the program encountered debug success but failed release, obviously is a very frustrating
, and often do not have the problem. If you look at the above analysis, combined with the specific performance of the error, quickly find the wrong

Mistake, is very good. But if you can't find out for a while, here are some strategies for this situation.


1. As mentioned earlier, Debug and release are just the differences between a set of compilation options, and there is virtually no definition to distinguish between them.
We can modify the release version of the compilation options to narrow the error range. As mentioned above, you can select the release
Item by note: That article is over, as if there were some.
In VC when the whole project is large, the software is often in the debug state can run in the release state is unable to run the situation. Since developers usually develop software in debug state, this is often done after two months of hard work and confidently preparing to release the software. In order to avoid unnecessary losses, we'd better conduct the following checks:
1, often test the two versions of software.
2, do not easily attribute the problem to the debug/release problem, unless you have fully tested the two versions.
3, pretreatment of different, also may cause such problems. One possibility of a problem is that different preprocessing tokens are defined between different versions of the compilation. Please try the following changes to your debug version of the software: in the Pro
Ject Setting (ALT-F7), set the directory (category) as "General" and Change "_de
BUG "is defined as" Ndebug ". Set the directory to "preprocessor" and add the definition "_DEBUG to" Undefined Sy
Mbols the input box. Select Rebuild all and recompile. If a compiled program has caused a problem, use the code
Make the following changes: Change assert () to VERIFY (). Find the code defined in "#ifdef _DEBUG," such as
The code needs to be moved to the definition outside of the release version. Find Trace (...) In the code, because this
Some of the code is not compiled in release. So please check carefully if the code that you need in release is not
Be cheap.

4, variable initialization brings about the difference, in different systems, or in the debug/release version of the differences exist, so please initialize the variable.


5. Do you already have a warning at compile time? Set the warning level to 3 or 4, and then ensure that no warnings appear at compile time.


6. Whether or not to change the resource file.


7, in addition to release version of the software can also be debugged, please make the following changes: In "Project Settings" under the "C++/C" Project set "category" to "General" and the "Debug Info" set to "program D Atabase ". Under the Link item, select the Generate Debug Info check box. "Rebuild All" so the practice will produce
Some of the limitations: The value of a variable in an MFC DLL cannot be obtained. All DLL works that are used by the software must be
Make changes. Another: A technical document from MS Bug:ms shows that in VC5 for DLLs "Maximize Spee

The D "Optimization option is not fully supported, so this can cause memory errors and cause the program to crash.


For the consolidated query, the sources are too numerous to list.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.