Null pointer dereference

Null pointer dereference

Description

Calling an instance method or accessing a field through a null reference in Java throws NullPointerException. Using a lookup result or external input without checking whether it exists may cause a request or task to fail.

Potential impact

  • An unhandled exception may interrupt a request or background task. Repeated failures can affect availability, but dereferencing an ordinary Java null reference does not by itself imply termination of the whole process or memory corruption.

Remediation

  1. Check inputs and lookup results that may be null before using them.
  2. Distinguish an expected missing value from a programming error, and provide the appropriate response or error handling.
  3. Validate required inputs and define clear return-value contracts.

Examples

Before

Declarations for userService, User and UserNotFoundException are omitted. Map the after example’s exception to an appropriate error response, and check that User.toString() does not expose sensitive information.

java
public class UserController {
    public String getUserById(HttpServletRequest request) {
        String userId = request.getParameter("id");
        User user = userService.findUserById(userId);
        return user.toString();  // Throws NullPointerException if user is null.
    }
}

After

java
public class UserController {
    public String getUserById(HttpServletRequest request) {
        String userId = request.getParameter("id");
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new UserNotFoundException("User not found for id: " + userId);
        }
        return user.toString();
    }
}

Explanation:

  • Before: findUserById may return null; immediately calling user.toString() then throws NullPointerException.
  • After: Checks the lookup result and throws an application-specific exception when no user exists, avoiding that null dereference.

Related CVEs

References