When your C++ program grows in size, it becomes difficult to keep track of its components, and it's easier to introduce bugs. So it is important to realize that some rules should be followed to write code more tolerant to errors.
This article provides some tips that may help you to write code more tolerant to critical errors (crashes). Even if your program currently doesn't follow any coding rules because of its complexity and because of your project's team structure, following the simple rules listed below may help you avoid the majority of crash situations.
For some softwares I develop, I have been using an Open-Source error reporting library called CrashRpt for a long time. The CrashRpt library allows to automatically submit error reports from installations of my software on users' computers. This way all critical errors (exceptions) in my software are automatically reported to me via the Internet, allowing me to improve my software and make users happier with each hot fix release.
While analyzing incoming error reports, I found that often the reason for program crashes can be easily avoided by following simple rules. For example, sometimes I forget to initialize a local variable and it might contain trash causing an array index overflow. Sometimes I don't perform a NULL
check before using a pointer variable and this causes an access violation.
I have summarised my experience in several coding rules below that may help you to avoid such mistakes and make your software more stable (robust).
Non-initialized local variables are a common reason for program crashes. For example, see the following code fragment:
The code fragment above can be a potential reason for a crash, because non of the local variables are initialized. When your code runs, these variables will contain some trash values. For example, the bExitResult
boolean variable may contain the value -135913245 (not boolean by nature). Or the szBuffer
string variable may not be zero-terminated as it must be. So initializing local variables is very important.
The correct code would be the following:
Note: One may say that for some time-critical calculations, variable initialization may be costly, and they are right. If your code should execute as rapidly as possible, you may skip variable initialization at your own risk.
Many WinAPI functions receive/return parameters through C structures. Such a structure, if incorrectly initialized, may be the reason for a crash. It is recommended to use the ZeroMemory()
macro or the memset()
function to fill structures with zeroes (this typically sets the structure fields to their default values).
Many WinAPI structures also have the cbSize
parameter that must be initialized with the size of the structure before using.
The following code shows how to initialize a WinAPI structure:
But! Do not use ZeroMemory()
or memset()
for your C++ structures that contain objects as structure members; that may corrupt their internal state and be the reason for a crash.But! Do not use ZeroMemory()
or memset()
for your C++ structures that contain objects as structure members; that may corrupt their internal state and be the reason for a crash.But! Do not use ZeroMemory()
or memset()
for your C++ structures that contain objects as structure members; that may corrupt their internal state and be the reason for a crash.But! Do not use ZeroMemory()
or memset()
for your C++ structures that contain objects as structure members; that may corrupt their internal state and be the reason for a crash.
It is even better to use a constructor for your C++ structure that would init its members with default values:
It is recommended to always validate function input parameters. For example, if your function is a part of the public API of a dynamic link library, and it may be called by an external client, it is not guaranteed that the external client will pass you the correct parameters.
For example, let's look at the hypothetical DrawVehicle()
function that draws a sports car on a window with a varying quality. The drawing quality nDrawingQaulity
may vary from 0 (coarse quality) to 100 (fine quality). The drawing rectangle in prcDraw
defines where to draw the car.
Below is the code. Note how we validate the input parameter values before using them.
Using a pointer without validation is very common. I would even say this is the main reason for crashes in my software.
If you use a pointer, make sure it is not equal to NULL
. If your code tries to use a NULL
pointer, this may result in an access violation exception.
If your function creates an object and returns it as a function parameter, it is recommended to initialize the pointer with NULL
in the beginning of the function body.
If you do not explicitly initialize the output parameter and further it is not set due to a bug in function logics, the caller may use the invalid pointer which would possibly cause a crash.
Here is an example of incorrect code:
The correct code:
Assign NULL
to a pointer after freeing (or deleting) it. This will help to ensure no one will try to reuse an invalid pointer. As you may suppose, accessing a pointer to a deleted object results in an access violation exception.
The following code example shows how to clean up a pointer to a deleted object.
Assign NULL
(or zero, or some default value) to a handle after freeing it. This will help ensure no one will try to reuse an invalid handle.
Below is an example of how to clean up a WinAPI file handle:
Below is an example of how to clean up a FILE*
handle:
If you allocate a single object with the operator new
, you should free it with the operator delete
.
But if you allocate an array of objects with the operator new
, you should free this array with delete []
.
or:
Sometimes it is required to allocate a buffer dynamically, but the buffer size is determined at run time. For example, if you need to read a file into memory, you allocate a memory buffer whose size is equal to the size of the file. But before allocating the buffer, ensure that 0 (zero) bytes are not allocated using malloc()
or new
. Passing the incorrect parameter to malloc()
results in a C run-time error.
The following code example shows dynamic buffer allocation:
For additional tips on how to allocate memory correctly, you can read the Secure Coding Best Practices for Memory Allocation in C and C++ article.
Asserts can be used in debug mode for checking pre-conditions and post-conditions. But when you compile your program in Release mode, asserts are removed on the pre-processing stage. So, using asserts is not enough to validate your program's state.
Incorrect code:
As you can see in the code above, usage of asserts can help you to check your program state in Debug mode, but in Release mod,e these checks will just disappear. So, in addition to asserts, you have to use if()
checks.
The correct code would be:
It is a common mistake to call the function and assume it will succeed. When you call a function, it is recommended to check its return code and values of output parameters.
The following code calls functions in succession. Whether to proceed or to exit depends on return code and output parameters.
If you intensively use pointers to shared objects (e.g., COM interfaces), it is a good practice to wrap them into smart pointers. The smart pointer will take care of your object's reference counting and will protect you from accessing an object that was already deleted. That is, you don't need to worry about controlling the lifetime of your interface pointer.
For additional info on smart pointers, see the following articles: Smart Pointers - What, Why, Which? and Implementing a Simple Smart Pointer in C++.
Below is an example code (borrowed from MSDN) that uses ATL's CComPtr
template class as a smart pointer.
Look at the following code fragment:
The code above is correct and uses pointer validation. But assume you made a typing mistake and used an assignment operator (=
) instead of the equality operator (==
):
As you can see from the code above, such mistyping may be the result of a stupid crash.
Such an error can be avoided by slightly modifying the pointer validation code (exchange left side and right side of the equality operator). If you mistype in such a modified code, it will be detected on compilation stage.
link:http://www.codeproject.com/KB/exception/MakingYourCodeRobust.aspx