Wiki Markup |
---|
Many functions accept pointers as arguments. If the function dereferences an invalid pointer (see [EXP34-C. Ensure a null pointer is not dereferenced]), or reads or writes to a pointer that does not refer to an object, the results are [undefined|BB. Definitions#undefined]. Typically, the program will terminate abnormally when thean invalid pointer is dereferenced, but it is possible, for an invalid pointer to be dereferenced, and its memory changed, without abnormal termination \[[Jack 07|AA. C References#Jack 07]\]. 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 if whether the pointer is valid or not, for some definition of valid. For example, the following function declares any pointer to be valid except NULL.
...
Noncompliant Code Example
This In this noncompliant code example, function increments the value pointed to 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.
Code Block | ||
---|---|---|
| ||
void incr(int *intptr) { if (intptr == NULL) { /* handleHandle error */ } *intptr++; } |
Compliant Solution
By In this compliant solution the incr()
function can be improved by using the valid()
function defined above, the 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.
Code Block | ||
---|---|---|
| ||
void incr(int *intptr) { if (!valid(intptr)) { /* handleHandle error */ } *intptr++; } |
The valid()
function can be implementation dependent and perform additional, platform dependent checks when possible.
Compliant Solution (assert
)
Because In this compliant solution because invalid pointers are often indicative of a bug defect in the program, the assert()
macro can be used to terminate immediately if an invalid pointer is discovered (see MSC11-C. Incorporate diagnostic tests using assertions).
...
Risk Assessment
A pointer validation library function can be used to identify detect and so prevent the execution of vulnerable code.Failure to clear memory can result in leaked information. Occasionally, it can also lead to buffer overflows if the program falsely assumes that a null-termination byte is presentprevent operations from being performed on some invalid pointers.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MEM10-C | high | unlikely | high | P3 | L3 |
...