[go: up one dir, main page]

CodeQL documentation

Access of invalid pointer

ID: rust/access-invalid-pointer
Kind: path-problem
Security severity: 7.5
Severity: error
Precision: high
Tags:
   - reliability
   - security
   - external/cwe/cwe-476
   - external/cwe/cwe-825
Query suites:
   - rust-code-scanning.qls
   - rust-security-extended.qls
   - rust-security-and-quality.qls

Click to see the query in the CodeQL repository

Dereferencing an invalid or dangling pointer may cause undefined behavior. Memory may be corrupted causing the program to crash or behave incorrectly, in some cases exposing the program to potential attacks.

Recommendation

When dereferencing a pointer in unsafe code, take care that the pointer is valid and points to the intended data. Code may need to be rearranged or additional checks added to ensure safety in all circumstances. If possible, rewrite the code using safe Rust types to avoid this kind of problem altogether.

Example

In the following example, std::ptr::drop_in_place is used to execute the destructor of an object. However, a pointer to that object is dereferenced later in the program, causing undefined behavior:

unsafe {
    std::ptr::drop_in_place(ptr); // executes the destructor of `*ptr`
}

// ...

unsafe {
    do_something(&*ptr); // BAD: dereferences `ptr`
}

In this case, undefined behavior can be avoided by rearranging the code so that the dereferencing comes before the call to std::ptr::drop_in_place:

unsafe {
    do_something(&*ptr); // GOOD: dereferences `ptr` while it is still valid
}

// ...

{
    std::ptr::drop_in_place(ptr); // executes the destructor of `*ptr`
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy