goplus / llgo

A Go compiler based on LLVM in order to better integrate Go with the C ecosystem including Python
Apache License 2.0
319 stars 26 forks source link

Unexpected nil pointer dereference when checking length of nil map #808

Open luoliwoshang opened 2 days ago

luoliwoshang commented 2 days ago

Unexpected nil pointer dereference when checking length of nil map An unexpected invalid memory address or nil pointer dereference error occurs when checking the length of a nil map using len(m) inside a function. The program successfully processes empty and non-empty maps but panics when attempting to process a nil map.

package main

import "fmt"

func processMap(m map[string]int) {
    if len(m) != 0 {
        fmt.Println("Map is not empty. Processing...")
        for k, v := range m {
            fmt.Printf("Key: %s, Value: %d\n", k, v)
        }
    } else {
        fmt.Println("Map is empty or nil. Nothing to process.")
    }
}

func main() {
    // normal
    emptyMap := make(map[string]int)
    fmt.Println("\nTesting with empty map:")
    processMap(emptyMap)

    // normal
    nonEmptyMap := map[string]int{"a": 1, "b": 2}
    fmt.Println("\nTesting with non-empty map:")
    processMap(nonEmptyMap)

    // panic
    var nilMap map[string]int
    fmt.Println("Testing with nil map:")
    processMap(nilMap)
}

Expected

Testing with empty map:
Map is empty or nil. Nothing to process.

Testing with non-empty map:
Map is not empty. Processing...
Key: a, Value: 1
Key: b, Value: 2
Testing with nil map:
Map is empty or nil. Nothing to process.

Got

Testing with empty map:
Map is empty or nil. Nothing to process.

Testing with non-empty map:
Map is not empty. Processing...
Key: b, Value: 2
Key: a, Value: 1

Testing with nil map:
panic: runtime error: invalid memory address or nil pointer dereference
luoliwoshang commented 2 days ago

https://github.com/goplus/llgo/pull/793 can resolve this issue