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
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.
Expected
Got