1134
If all pointers that could have been modified are sanity-checked previous to use, nearly all NULL
pointer dereferences can be prevented.
Phase: Requirements
The choice could be made to use a language that is not susceptible to these issues.
Phase: Implementation
Check the results of all functions that return a value and verify that the value is non-null before
acting upon it.
Effectiveness = Moderate
Checking the return value of the function will typically be sufficient, however beware of race
conditions (CWE-362) in a concurrent environment. This solution does not handle the use of
improperly initialized variables (CWE-665).
Phase: Architecture and Design
Identify all variables and data stores that receive information from external sources, and apply
input validation to make sure that they are only initialized to expected values.
Phase: Implementation
Explicitly initialize all your variables and other data stores, either during declaration or just before
the first usage.
Phase: Testing
Use automated static analysis tools that target this type of weakness. Many modern techniques
use data flow analysis to minimize the number of false positives. This is not a perfect solution,
since 100% accuracy and coverage are not feasible.
Demonstrative Examples
Example 1:
While there are no complete fixes aside from conscientious programming, the following steps will
go a long way to ensure that NULL pointer dereferences do not occur.
Example Language: (Good)
if (pointer1 != NULL) {
/* make use of pointer1 */
/* ... */
}
If you are working with a multithreaded or otherwise asynchronous environment, ensure that proper
locking APIs are used to lock before the if statement; and unlock when it has finished.
Example 2:
This example takes an IP address from a user, verifies that it is well formed and then looks up the
hostname and copies it into a buffer.
Example Language: C (Bad)
void host_lookup(char *user_supplied_addr){
struct hostent *hp;
in_addr_t *addr;
char hostname[64];
in_addr_t inet_addr(const char *cp);
/*routine that ensures user_supplied_addr is in the right format for conversion */
validate_addr_form(user_supplied_addr);
addr = inet_addr(user_supplied_addr);
hp = gethostbyaddr( addr, sizeof(struct in_addr), AF_INET);
strcpy(hostname, hp->h_name);
CWE Version 4.14
CWE-476: NULL Pointer Dereference
CWE-476: NULL Pointer Dereference