Visual c ++ debugging: How to Use 'assert 'and deal with assertions failures?

Source: Internet
Author: User

Http://forums.codeguru.com/showthread.php? 315371-visual-c-debugging-how-to-use-assert-and-deal-with-assertions-failures

Q:What is an assertion?

A:An assertion statement specifies a condition that you have CT to hold true at some particle point in your program. if that condition does not hold true, the assertion fails, execution of your program is interrupted, and the assertion failed
Dialog box appears.

Q:What kind of asserts does visual c ++ support?

A:Visual c ++ supports assertion statements based on the following constructs:

  • 'Mfc asserexception' for MFC Program
  • 'Atlassert for programs that Use ATL
  • 'Crt 'assertions for programs that use the C run-time Library
  • ANSI 'assert () 'function for other C/C ++ programs

Q:What good are assertions?

A:You can use assertions:

  • Catch logic errors
  • Check Results of an operation
  • Test error conditions that shoshould have been handled

Q:What is MFC's assert?

A:A macro definition that allows you to evaluate an expression. if the expression is evaluated to 0, the macro prints a Diagnostic message and aborts the program. if the condition is nonzero, it does nothing. the Diagnostic message has
Form

Code:
assertion failed in file _filename_ in line _linenum_

Where '_ filename _' is the name of the source file, and '_ linenum _' is the line number of the assertion that failed in the source file. in an mfc isapi application, an assertion in debug mode will bring up a modal dialog box; this will interrupt or hang
Execution.

Q:Are there another MFC assertion Macros?

A:Yes, you can also use one of these:

  • 'Assert _ kindof (classname, pobject) '-> This macro asserts that the object pointed to is an object of the specified class, or is an object of A Class derived from the specified class.

    Code:
    ASSERT_KINDOF(CMyDocument, pDocument)

    If identical

    Code:
    ASSERT(pobject->IsKindOf(RUNTIME_CLASS(classname)));

  • 'Assert _ valid (pobject) '-> used to test an assumptions about the validity of an object's internal state. the parameter must be an object of A Class derived from 'object' that has an overriding version
    Of the 'assertvalid () 'member function. 'assert _ valid' validates the pointer, checks against 'null', and CILS the object's own 'assertvalid ()' member functions.

Q:What about 'atlassert '?

A:The 'atlassert 'macro performs the same functionality as the' _ asserte 'macro found in the C run-time library.

Q:What are the CRT assertion Macros?

A:The 'crtdbg. H' header file defines the '_ assert' and '_ asserte' macros for assertion checking. The result of these macros are:

  • '_ Assert: if the specified expression evaluates to false, the file name and line number of the _ assert
  • '_ Asserte': Same as _ assert, plus a string representation of the expression that was asserted

Q:How do I chose between '_ assert' and '_ asserte '?

A:'_ Asserte' is more powerful because it reports the asserted expression that turned out to be 'false '. this may be enough to identify the problem without referring to the source code. however, the debug version of your application will contain
A String constant for each expression asserted using '_ asserte '. if you use your '_ asserte' macros, these string expressions take up a significant amount of memory. if that proves to be a problem, use '_ assert' to save memory.

Q:And about the ANSI assertion funtion?

A:'Assert () 'Evaluates an expression and, when the result is 'false', prints a Diagnostic message and aborts the program.

The ANSI 'assert 'macro is typically used to identify logic errors during program development by implementing the expression argument to evaluate to 'false' only when the program is operating incorrectly. after debugging is complete, assertion checking can
Be turned off without modifying the source file by defining the identifier 'ndebug '. 'ndebug' can be defined with a'/d' command-line option or with a' # define 'ctictive. if 'ndebug' is defined with '# define', the directive must appear before 'assert. h'is
Encoded ded.

'Assert 'prints a Diagnostic message when expression evaluates to 'false' (0) and callabort to terminate program execution. no action is taken if expression is 'true' (nonzero ). the Diagnostic message provided des the failed expression and the name of the source
File and line number where the assertion failed.

Q:Can I see an example of 'assert ()'?

A:Here is a simple example and the output. Consider the file is called 'test. cpp ':

Code:
#include <assert.h>int main(){  int* array = NULL;  assert(array != NULL);  // this should fail  return 0;}

Output is:

Code:
Assertion failed: array != NULL, file test.cpp, line 7abnormal program termination

Q:Do asserts work in release version also?

A:No, only in debug version. in the release version of MFC, 'assert 'does not evaluate the expression and thus will not interrupt the program. if the expression must be evaluated regardless of environment, use the 'verify 'macro in place
'Assert '. because of this, never use a method that changes the state of the program as the expression or part of the expression of 'assert '. in a release build, 'assert 'is not supported in the code.

Code:
class foo{  int n;public:   foo() : n(0) {}   void getN() const {return n;}   bool incrementN()  {    n++;     return true;  }};int main(){   foo _foo;   ASSERT(0 == _foo.getN()); // OK, the state is not altered   // a call to incrementN() is supposed to follow, which alters the state    ASSERT(_foo.incrementN()); // WRONG, works only in Debug; in Release incrementN() never gets called}

Q:What shoshould I do when I get a "Debug assertion failed! "Message?

A:Run your application in debugger and when you get the message press 'retry' to debug the application. look in the 'call stack' window (Alt + 7) and go to the first (from top down) function written by you in the stack and identify the line
That triggers the assertion failure.

Q:What are common causes for assertion failures?

A:Most often it is the usage of an invalid pointer or an attempt to index an array beyond its boundaries.

Q:How can 'assert 'Help Me With writing better code?

A:You build your application first as a debug version and only when it is finished you build the release version. 'assert 'help you identify the errors in the execution flow. you shoshould always test pointers for validity:

Code:
void Draw(int index){   CFigure* pFigure = GetFigure(index); // should return a figure from a list    // if GetFigure returns NULL the next line of code is faulty   pFigure->Draw ();}

The correct way is:

Code:
void Draw (int index){   CFigure* pFigure = GetFigure(index);   ASSERT(pFigure != NULL);  // if pFigure == NULL you get an error message   if(pFigure == NULL)  // this avoids the usage of a NULL pointer      return;   pFigure->Draw ();}

In this example, I consider 'getfigure () 'A function that shoshould always return a valid figure. the role of 'assert 'is to ensure that 'getfigure ()' actually does what it supposed to do and always return a valid pointer. now if you wander what is the role

Code:
if(pFigure == NULL)  return;

The answer is to make sure that if the debug build wasn' t tested enough and an error cocould occur in the release, the program wouldn't crash because of the use of a 'null' pointer.

However, if 'getfigure () 'can return a 'null' pointer, that pointer shoshould not be asserted against 'null '.

You shoshould also test the index used for accessing elements of Arrays:

Code:
// this is a dummy exampleclass foo{   int elements[10];public:   foo() { /* do some initialization */ };   int getAt(int index) const    {     ASSERT(index>=0 && index<10);     if(index>=0 && index<10)       return elements[index];         return -1; // return a default value   }};

Last edited by Andreas Masur; July 25th, 2005 at AM.

Related Article

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.