Thursday, May 2, 2024
HomeGolangIntriguing Pointer Equality Conduct on Zero-Width Sorts - Technical Dialogue

Intriguing Pointer Equality Conduct on Zero-Width Sorts – Technical Dialogue


I’d wish to report an intriguing habits concerning the pointer equality of zero-width varieties. Apologies if that is trivial or a recognized situation.

The 2 codes beneath seem like similar, but the outcomes of &a == &b differ. It appears predictable that “variables go into separate addresses on the stack, until pointers are wanted”, versus “variables escape to the identical handle on the heap, when pointers are wanted,”.

// go1.20.5 darwin/arm64

// go run enter.go
func most important() {
	var a, b struct{}
	fmt.Println(&a == &b) // false
}

// go construct -gcflags="-m -N -l" -o output enter.go
// # command-line-arguments
// ./enter.go:9:13: ... argument doesn't escape
// ./enter.go:9:17: &a == &b escapes to heap
// go1.20.5 darwin/arm64

// go run enter.go
func most important() {
	var a, b struct{}
	fmt.Println(&a == &b)  // true
	fmt.Printf("%pn", &a) // 0x1172f60 *is dependent upon env
	fmt.Printf("%pn", &b) // 0x1172f60 *is dependent upon env
}

// go construct -gcflags="-m -N -l" -o output enter.go
// # command-line-arguments
// ./enter.go:8:6: moved to heap: a
// ./enter.go:8:9: moved to heap: b
// ./enter.go:9:13: ... argument doesn't escape
// ./enter.go:9:17: &a == &b escapes to heap
// ./enter.go:10:12: ... argument doesn't escape
// ./enter.go:11:12: ... argument doesn't escape

Is that this outlined habits, undefined habits, or a bug?
Please present any insights or suggestions that you just may need.
Thanks.

The comparability operators part of the language specification says this about pointers:

Tips that could distinct zero-size variables could or might not be equal.

And the final sentence of the language specification says:

Two distinct zero-size variables could have the identical handle in reminiscence.

However that doesn’t imply that they must. I’m not conscious if wherever the standards for when that occurs is specified; I think it’s an implementation element of the compiler.

1 Like

@skillian

I’m glad to seek out out that it’s clearly written within the specs that I wish to know!
In response to this textual content, it looks as if this habits just isn’t outlined.

Any further, I’m going to ensure to test the language specs myself.
Thanks!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments