C ++ is a mainstream development language for desktop systems, especially system software and large-scale application software. C ++ is known for its flexibility and complexity. Using C ++ to write robust code is more challenging. C ++ allows dynamic memory management and can easily cause more memory-related problems. In general, apart from system design defects, C ++-Based Software defects and errors are mostly related to memory defects (mainly including memory access errors and memory leaks. Therefore, Eliminating Memory-related defects in the Code has become a task for programmers to write, debug, and maintain code. It is also the key to ensuring software quality.
This article is based on the "863" project "large-scale GIS for massive network space information. The system is written based on C ++/MFC and the development environment is Visual Studio. net 2003. Based on the engineering practices of this project, it summarizes the methods and tools for using the C ++ language mechanism, development environment, and Related Quality Assurance tools to prevent and discover various defects related to compilation, runtime, and memory.
1. Compliance with C ++ coding standards and practices to prevent Defects
Coding standards are language-related rules and are lessons learned from practice. Good programming standards will effectively help developers avoid developing potentially dangerous code. Generally, to reduce memory defects, the following encoding rules should be followed:
(1) The destructor of a base class or class with a virtual function should be declared as a virtual function.
(2) prevent memory leakage in constructor. Do not throw exceptions in destructor.
(3) Use the corresponding form of new and delete. That is, delete is used to release the memory applied for new. delete [] releases the memory applied for by new.
(4) the pointer must be initialized before use. The pointer pointing to the dynamic memory should be set to null immediately after being released.
(5) if resources are allocated to the class constructor, You need to explicitly provide the copy constructor and the value assignment operator, and release resources in the destructor.
It is worth noting the conventional usage of RAII in C ++. The core idea of RAII is to use objects to manage resources, obtain resources in object constructors, and release resources in their destructor [2]. To ensure that the dynamically applied memory can be released even when exceptions occur, it is ideal to use local variables to manage the ownership of the dynamic memory (ownership ), is the so-called smart pointer. Auto_ptr in STL is designed to solve the problem of resource ownership, but it lacks support for the number of references and arrays and cannot be used in STL containers. The Boost Library [3] provides relatively mature smart pointers with high practical value. The shared_ptr thread is secure and can be used in STL containers. For more information, see [3].
1.1 CodeWizard
CodeWizard can automatically scan, analyze, and check the source program. Once an violation is found, information is generated to indicate which rule does not match and an explanation is given. Taking CodeWizard 4.3 as an example, more than 500 encoding standards are built in. CodeWizard can select the encoding standards to be executed for the current project. CodeWizard can be closely integrated with VC ++. After installation, there will be a CodeWizard toolbar in VC ++.
1.2 code check tool PC-Lint
PC-Lint can check for errors that are not easily discovered by the compiler. PC-Lint can check more than 100 C-library functions and discover more than common errors in Standard C/C ++ code. To integrate PC-lint with Visual Studio, you must configure it yourself. Jon Zyzyck provides a Report Generator to help with this task. . Document [4] explains how to integrate PC-Lint in the VC ++ environment.
2. Use language mechanisms, development environments, and related tools to prevent and detect memory Defects
Discovering a problem is a prerequisite for solving the problem. Compared with fixing memory defects, it is more time-consuming and labor-consuming to discover memory defects and accurately locate the code that causes the defects. Early and accurate detection of memory defects is very important for improving development efficiency.
2.1 Early Exposure of memory defects using assertions
Assertions are Boolean debugging statements used to check whether the value of a condition is always true when the program is running. Assertions are often used to confirm the input and output of functions, and check whether the current status of the function is valid. Assertions can be used in the following scenarios to help identify errors related to illegal memory access:
(1) verify whether the pointer is readable/written. At the function entrance, it is often necessary to verify whether the content area pointed to by the pointer is readable/written. Usually assert (p! = NULL. However, if the pointer value is not null, it does not mean that the Pointer Points to the legal read/write memory. Win32 API provides functions such as IsBadReadPtr, IsBadWritePtr, IsBadStringPtr, and IsBadCodePtr to detect whether the memory area pointed to by the pointer is readable/written. The C Runtime Library provides functions such as _ CrtIs ValidPointer and _ CrtIsValidHeapPointer. The MFC Library provides functions such as AfxIsValidAddress and AfxIsValidString to complete similar functions.
(2) For an MFC-based program, the ASSERT_VALID macro calls the overloaded AssertValid function to determine whether the pointer to the CObject derived class object is valid. The ASSERT_VALID macro mainly calls the AfxIsValidAddress function and the AssertValid function of the CObject derived class Object (refer to the source code afx. h and objcore. cpp of MFC ).
2.2 Use the C Runtime Library to check memory leakage
The C Runtime Library (CRT) of VC ++ provides a wide range of functions to help users detect memory leaks. CRT provides functions such as _ CrtMemCheckPoint, _ CrtDump MemoryLeaks, and _ CrtSetDbgFlag to help debug memory leaks.
For non-MFC projects, to enable the effective Memory Leak report function, you need to perform the following settings:
(1) Add the following code in the StdAfx. h header and enable the compiler/Yu option:
1. # define _ CRTDBG_MAP_ALLOC
2. # include <stdlib. h>
3. # include <crtdbg. h>
4. # define DEBUG_NEW (_ NORMAL_BLOCK, THIS_FILE, _ LINE __)
(2) ensure that the header of each. cpp file contains the following content:
1. # include "stdafx. h"
2. # ifdef _ DEBUG
3. # define new DEBUG_NEW
4. # undef THIS_FILE
5. static char THIS_FILE [] = _ FILE __;
6. # endif
(3) Enable the report Memory leakage switch at the beginning of the program:
_ CrtSetDbgFlag (_ CRTDBG_ALLOC_MEM_DF | _ CRTDBG_LEAK_CHECK_DF );
For the MFC project, MFC has done the relevant work, just confirm that the header of each. cpp file contains the content at (2) above.
In some cases, you need to know the content of the memory block in which memory leakage occurs, but the standard memory dump is only in the hexadecimal format of the memory block header. To obtain more useful information, you need to apply for memory as a user BLOCK (_ CLIENT _ BLOCK) and use _ CrtSetDumpClient to create a dump function for user BLOCK memory. Specifically, for classes not inherited from CObject, You need:
(1) specify a user block subtype for each class/Structure (refer to crtdbg. h ).
(2) When applying for memory, use the reloaded new form: void * _ cdecl operator new (size_t nSize, int nType, LPCSTR lpszFileName, int nLine) (refer to the source code afxmem of MFC. cpp), where nType is the child type of the user block.
(3) create a user block memory dump function to process each sub-type to be dump (which must contain dbgint. h ).
(4) use _ CrtSetDumpClient to register the user block memory dump function (refer to the MFC source code dumpinit. cpp ).
For Classes inherited from CObject, MFC has done the basic work according to the above method (refer to the MFC source code afxmem. cpp, dumpinit. cpp ). To effectively Dump objects inherited from CObject, You need to: (1) Reload the virtual function Dump for each class inherited from CObject. (2) Add the code afxDump. SetDepth (1) in the initialization part of the program to enable the deep dump.
2.3 use Purify and Insure ++ to find runtime memory Defects
Rational Purify and Parasoft Insure ++ are tools used for runtime error checks. Purify mainly checks: Array Memory out-of-bounds read/write, use uninitialized memory, read/write the released memory, and memory leakage. Insure ++ uses its patented technology (source code plug-in and runtime pointer tracking) to detect a large number of Memory Operation errors and Report incorrect source code lines and execution tracks. According to the author's test (based on 98 C ++ programs with various memory errors, covering typical cases), Insure ++ 6.1 can be accurately detected.
3. Use the debugging and diagnosis functions in the VC ++ environment to check and discover common memory Defects
Understanding common memory defect problems and symptoms in the VC ++ environment can help us reduce the problem occurrence and timely modify the problem.
Stack-related errors are classified into two types: Stack Overflow and function return information destruction.
(1) Stack overflow)
There are two main scenarios for such errors:
1) excessive local variables. By default, Windows reserves 1 MB of stack space for each thread. Choose Project> Properties> Configuration Properties> Linker> System. The Stack Reserve Size Option is displayed to adjust the Size of the reserved Stack space.
2) The number of recursive calls is too deep. During the debugging process, the call stack window shows the recursive call mode of the function.
(2) Information returned by the function is damaged.
There are two main scenarios for such errors:
1) write operations on local variables are out of the range (overflow ). During the debugging process, the obvious indicator of the function stack being destroyed is that the call stack cannot be displayed, and the error occurs in the location where the called function is about to return.
2) If there is a mismatch between the called function and the called function, or the call specification is inconsistent.
To check for such errors, enable/GS and/RTCs during Code compilation (in the menu Project> Properties> Configuration Properties> C/C ++> Code Generation ).
Another type of error is a dynamic memory error. The typical situation is as follows:
(1) memory write out of bounds. In the debugging version, if the write overflow occurs, the system will receive "Damage: after block... ", if it is a write overflow, it will receive" Damage: before block....
(2) Delete invalid pointers. In the debugging version, when uninitialized or non-heap pointers are deleted, the _ CrtIsValidHeapPointer asserted error is returned.
(3) Multiple releases. In the debug version, if you delete the same pointer multiple times, the _ BLOCK_TYPE_IS_VALID asserted error is returned. To prevent such errors, delete a pointer to the dynamic memory and immediately leave it blank.
4. Use Windows structured exception handling mechanism to handle memory crashes of released software versions
During the program release stage, program errors, especially memory crashes, should be minimized. If the program crashes, you should exit elegantly and try to collect running information when the program crashes to help the program supplier with subsequent debugging. To capture illegal memory access and obtain the instruction address and register content for illegal access, you need to use the Windows Structured Exception Handling (SEH) mechanism [6]. MiniDumpWriteDump is dbghelp. an API function provided by dll (refer to MSDN), used to dump some information of user mode programs (such as stack conditions) and co-exist as a file (such. dmp file). This file can be used by Microsoft's debugger (VC ++ or WinDBG) for post-event debugging. Using this function requires dbghelp. h, dbghelp. lib, and dbghelp. dll (these files can be found in the Windows Platform SDK ).
To debug the code based on the. dmp file afterwards, you need to generate the DEBUG symbols (pdb) file for the released software version (enable the compiler/debug option ). After obtaining the. dmp file, use VC ++ to open the. dmp file and debug the file (Press F5 ). In this way, the crash scene will reappear. Document [5] implements the crash reporting system based on the above method. Www.2cto.com
5 conclusion
Practice has proved that the methods and tools to reduce Software Memory defects supported by the above methods and tools can effectively prevent and find out memory errors and memory leaks in the code, in addition, it can be seamlessly integrated with the daily coding of developers and can be executed very efficiently. The above methods work with unit testing, code review, daily building, Bug tracking, and other measures to form an efficient quality assurance process, which plays an important role in the software development process of our large-scale platform.
References
1 Sutter H, Alexandrescu A. C ++ Coding Standards: 101 Rules, Guidelines, and Best Practices [M]. Addison-Wesley Professional, 2004-10.
2 Stroustrup B. The Design and Evolution of C ++ [M]. Addison-Wesley Professional, 1994-03.
3 Karlsson B. Beyond the C ++ Standard Library: An Introduction to Boost [M]. Addison-Wesley Professional, 2005-08.
4 Zyzyck J. A Report Generator for PC-Lint [J]. Dr. Dobb's Journal, 2003, 28 (2): 52.
5 Dietrich H. XCrash Report: Exception Handling and Crash Reporting [Z]. 2003-10. http://www.codeproject.com/debug/ XCrash ReportPt4.asp.
6 Richter j m. Programming Applications for Microsoft Windows [M]. Microsoft Press, 1999-09.
Author: zhongguoren666