# Missing Check against Null

#### Tools recognizing this:

<kbd>Opengrep</kbd> <kbd>Fortify</kbd> <kbd>Checkmarx</kbd> <kbd>SonarQube</kbd> <kbd>Snyk</kbd> <kbd>Semgrep</kbd> <kbd>CodeQL</kbd>

## What is Missing Check against Null and How Does it Work?

Missing Check against Null is a common programming vulnerability that occurs when code fails to verify if an object reference is null before using it. This can lead to null pointer exceptions (NPEs) at runtime, causing application crashes and potential security vulnerabilities.

The absence of null checks can result in:

* Application crashes and unexpected termination
* System instability and poor user experience
* Potential security vulnerabilities through error messages
* Resource leaks and memory issues

This guide covers Missing Check against Null issues, examples, prevention methods, and how to properly handle null references using real-world techniques.

## One Simple Missing Check against Null Example

Consider this classic example of accessing an object without null checking:

{% code overflow="wrap" %}

```
User user = getUserFromDatabase();
String username = user.getUsername();  // Could throw NullPointerException if user is null
```

{% endcode %}

If getUserFromDatabase() returns null, this code will throw a NullPointerException when trying to access getUsername().

The safer version would be:

<kbd>User user = getUserFromDatabase();</kbd> <kbd>String username =</kbd> <kbd><mark style="color:red;">user != null ? user.getUsername() : "default";<mark style="color:red;"></kbd>

This ensures the code handles the null case gracefully instead of throwing an exception.

## Null Check Prevention Methods: How to Fix Your Code

The most efficient way to fix Missing Check against Null issues is by using proper null checking mechanisms and modern language features designed for null safety.

These include using the Optional pattern, null-safe operators, Objects.requireNonNull(), and explicit null checks where appropriate.

### Code Samples

{% tabs %}
{% tab title="Java" %}
**Vulnerable Code**

<pre class="language-java"><code class="lang-java">public void processUser(User user) {
    String name = <a data-footnote-ref href="#user-content-fn-1">user.getName()</a>;
    System.out.println("Processing user: " + name);
}
</code></pre>

**Fixed Code**

```java
public void processUser(User user) {
    Objects.requireNonNull(user, "User cannot be null");
    String name = user.getName();
    System.out.println("Processing user: " + name);
}
```

**Fix Explanation**

The vulnerable code assumes user is never null.The fix uses Objects.requireNonNull() to validate the parameter.This provides a clear error message if null is passed.The check happens early, preventing deeper issues in the method.
{% endtab %}

{% tab title="JavaScript" %}
**Vulnerable Code**

```javascript
function processUser(user) {
    const name = user.name;
    console.log(`Processing user: ${name}`);
}
```

**Fixed Code**

```javascript
function processUser(user) {
    if (!user) {
        throw new Error('User cannot be null');
    }
    const name = user.name ?? 'Unknown';
    console.log(`Processing user: ${name}`);
}
```

**Fix Explanation**

The vulnerable code doesn't check if user exists.The fix adds an explicit null check at the start.Uses the nullish coalescing operator (??) for safe property access.Provides a clear error message when null is passed.
{% endtab %}

{% tab title="Python" %}
**Vulnerable Code**

```python
def process_user(user):
    name = user.name
    print(f"Processing user: {name}")
```

**Fixed Code**

```python
def process_user(user):
    if user is None:
        raise ValueError("User cannot be None")
    name = getattr(user, 'name', 'Unknown')
    print(f"Processing user: {name}")
```

**Fix Explanation**

The vulnerable code assumes user is never None.The fix adds an explicit None check.Uses getattr() with a default value for safe attribute access.Raises a descriptive ValueError if None is passed.
{% endtab %}

{% tab title="C#" %}
**Vulnerable Code**

```csharp
public void ProcessUser(User user)
{
    string name = user.Name;
    Console.WriteLine($"Processing user: {name}");
}
```

**Fixed Code**

```csharp
public void ProcessUser(User user)
{
    ArgumentNullException.ThrowIfNull(user);
    string name = user.Name ?? "Unknown";
    Console.WriteLine($"Processing user: {name}");
}
```

**Fix Explanation**

The vulnerable code doesn't validate the user parameter.The fix uses ArgumentNullException.ThrowIfNull for parameter validation.Uses the null-coalescing operator (??) for safe property access.Follows C# best practices for null checking.
{% endtab %}

{% tab title="PHP" %}
**Vulnerable Code**

```php
function processUser($user) {
    $name = $user->name;
    echo "Processing user: " . $name;
}
```

**Fixed Code**

```php
function processUser(?User $user) {
    if ($user === null) {
        throw new InvalidArgumentException('User cannot be null');
    }
    $name = $user->name ?? 'Unknown';
    echo "Processing user: " . $name;
}
```

**Fix Explanation**

The vulnerable code assumes $user is never null.The fix adds type hinting with nullable operator (?).Includes explicit null check with clear error message.Uses the null coalescing operator (??) for safe property access.
{% endtab %}

{% tab title="C/C++" %}
**Vulnerable Code**

```cpp
void processUser(User* user) {
    string name = user->getName();
    cout << "Processing user: " << name << endl;
}
```

**Fixed Code**

```cpp
void processUser(User* user) {
    if (user == nullptr) {
        throw invalid_argument("User cannot be null");
    }
    string name = user->getName();
    cout << "Processing user: " << name << endl;
}
```

**Fix Explanation**

The vulnerable code doesn't check for null pointer.The fix adds explicit nullptr check.Throws an exception with clear error message if null.Prevents undefined behavior from dereferencing null pointer.
{% endtab %}
{% endtabs %}

## Need more help in preventing Missing Check against Null?

[Mobb](https://mobb.ai) supports fixing many forms of Missing Check against Null vulnerabilities, and can mitigate your issues in batch.

Start now for free at [app.mobb.ai](https://app.mobb.ai)

### We'd love your feedback!

We're excited to hear your thoughts and ideas about fixing vulnerabilities.

[Book a meeting](https://calendly.com/mobbai/demo) or [Contact us](https://content.mobb.ai/contact) if you have any corrections, questions or suggestions. Start now for free at <https://app.mobb.ai>

[^1]: This is the vulnerable part


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.mobb.ai/mobb-user-docs/fixing-guides/missing-check-againt-null-fix-guide.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
