methods for using the Assert function under Linux systems.
The steps are as follows:
The stereotype of an Assert macro is defined in "Assert.h", which terminates the execution of a program if its condition returns an error, and the prototype defines:
#include "Assert.h"
void assert (int expression);
The function of assert is to calculate the expression expression, if its value is false (that is, 0), then it first prints an error message to stderr.
The program is then terminated by calling abort.
Please see the following list of programs BADPTR.C:
#include "stdio.h"
#include "Assert.h"
#include "Stdlib.h"
int main (void)
{
FILE *FP;
fp = fopen ("Test.txt", "w"),//open a file in a writable manner, and create a file with the same name if it does not exist
ASSERT (FP); So there's no mistake.
Fclose (FP);
fp = fopen ("Noexitfile.txt", "R"),//open a file as read-only, failure to open file if not present
ASSERT (FP); So there's a mistake.
Fclose (FP); The program will never be executed here.
return 0;
}
[Root@localhost error_process]# gcc badptr.c
[Root@localhost error_process]#. /a.out
A.out:badptr.c:14:main:assertion ' FP ' failed.
Has abandoned
The disadvantage of using assert is that frequent calls can greatly affect the performance of your program and add additional overhead.
After debugging, you can disable an assert call by inserting a #define NDEBUG before the statement that contains the #include "Assert.h", the sample code is as follows:
#include "stdio.h"
#define Ndebug
#include "Assert.h"
Usage summary and ATTENTION matters:
1 Verify the validity of the incoming parameter at the beginning of the function
Such as:
int resetbuffersize (int nnewsize)
{
Function: Change the buffer size,
Parameters: Nnewsize Buffer new length
Return value: Buffer current length
Note: Keep the original information content unchanged Nnewsize =0 indicates clear buffer
ASSERT (nnewsize = 0);
ASSERT (nnewsize = max_buffer_size);
。。。
}
2 Each assert checks only one condition, because when multiple conditions are checked, if the assertion fails, it is not intuitive to determine which condition failed
Bad: Assert (noffset "=0 && noffset+nsize" =m_ninfomationsize);
OK: assert (noffset = 0);
ASSERT (noffset+nsize = m_ninfomationsize);
3 cannot use statements that alter the environment, because assert only takes effect in debug, and if you do so, you will use the program to run into problems when you are actually running
Error: Assert (i++ 100)
This is because if an error occurs, such as i=100 before execution, then the statement is not executed, and i++ This command is not executed.
Correct: Assert (i, 100)
i++;
4 Assert and subsequent statements should be empty line to form a logical and visual sense of consistency
5 in some places, assert cannot replace conditional filtering