Null Pointer Dereference Medium

Dereferencing a null pointer can lead to unexpected null pointer exceptions. Consider adding a null check before dereferencing the pointer.

Detector ID
kotlin/null-pointer-dereference@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1// Noncompliant: Dereferencing freed pointer
2fun noncompliant() {
3    val byteBuffer = ByteBuffer.allocateDirect(Int.SIZE_BYTES)
4    val ptr = byteBuffer.asIntBuffer()
5    byteBuffer.clear()
6    val value = ptr[0] 
7}

Compliant example

1// Compliant: Added a null check before dereferencing the pointer.
2fun compliant() {
3    val byteBuffer = ByteBuffer.allocateDirect(Int.SIZE_BYTES)
4    val ptr = byteBuffer.asIntBuffer()
5    if(ptr != null) {
6        val value = ptr[0] 
7        byteBuffer.clear()
8    }
9}