Skip to content

fix: return error instead of panicking when MapTo receives a nil pointer#379

Open
Yanhu007 wants to merge 1 commit intogo-ini:mainfrom
Yanhu007:fix/mapto-nil-pointer-panic
Open

fix: return error instead of panicking when MapTo receives a nil pointer#379
Yanhu007 wants to merge 1 commit intogo-ini:mainfrom
Yanhu007:fix/mapto-nil-pointer-panic

Conversation

@Yanhu007
Copy link
Copy Markdown

Fixes #369

Problem

When MapTo is called with a pointer to a nil struct pointer, the code dereferences once and then operates on the nil value, causing a panic:

var cfg *Config // nil
f.MapTo(&cfg)  // panics!

Fix

Add a loop after the initial pointer unwrap to handle nested pointers. If a nil pointer is encountered, return a clear error instead of panicking:

for val.Kind() == reflect.Ptr {
    if val.IsNil() {
        return errors.New("cannot map to a nil pointer")
    }
    typ = typ.Elem()
    val = val.Elem()
}

All existing tests pass.

When MapTo is called with a pointer to a nil struct pointer
(e.g. MapTo(&nilPtr)), the code dereferences the pointer once
and then operates on the nil value, causing a panic.

Add a loop to handle nested pointer types, returning a clear
error message when a nil pointer is encountered.

Fixes go-ini#369
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

panic: nil struct pointer to MapTo

1 participant