Many functions accept pointers as arguments. If the function dereferences an invalid pointer (as in EXP34-C. Do not dereference null pointers) or reads or writes to a pointer that does not refer to an object, the results are undefined. Typically, the program will when an invalid pointer is dereferenced, but it is possible for an invalid pointer to be dereferenced and its memory changed without abnormal termination [Jack 2007]. Such programs can be difficult to debug because of the difficulty in determining if a pointer is valid.
One way to eliminate invalid pointers is to define a function that accepts a pointer argument and indicates whether or not the pointer is
Some platforms have platform-specific pointer validation tools.
The following code relies on the
_etext address, defined by the loader as the first address following the program text on many platforms, including AIX, Linux, QNX, IRIX, and Solaris. It is not POSIX-compliant, nor is it available on Windows.
On a Linux platform, this program produces the following output:
valid() function does not guarantee validity; it only identifies null pointers and pointers to functions as invalid. However, it can be used to catch a substantial number of problems that might otherwise go undetected.
Noncompliant Code Example
In this noncompliant code example, the
incr() function increments the value referenced by its argument. It also ensures that its argument is not a null pointer. But the pointer could still be invalid, causing the function to corrupt memory or terminate abnormally.
incr() function can be improved by using the
valid() function. The resulting implementation is less likely to dereference an invalid pointer or write to memory that is outside the bounds of a valid object.
valid() function can be implementation dependent and perform additional, platform-dependent checks when possible. In the worst case, the
valid() function may only perform the same null-pointer check as the noncompliant code example. However, on platforms where additional pointer validation is possible, the use of a
valid() function can provide checks.
A pointer validation function can be used to detect and prevent operations from being performed on some invalid pointers.
|LDRA tool suite|
|159 S||Enhanced enforcement|
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
|SEI CERT C++ Coding Standard||VOID MEM10-CPP. Define and use a pointer validation function|
CWE-20, Improper Input Validation