Remix.run Logo
simiones 4 days ago

The confusion begins the moment you think Go variables get allocated on the stack, in the C sense. They don't, semantically. Stack allocation is an optimization that the Go compiler can sometimes do for you, with no semantics associated with it.

The following Go code also works perfectly well, where it would obviously be UB in C:

  func foo() *int {
    i := 7
    return &i
  }

  func main() {
    x := foo()
    fmt.Printf("The int was: %d", *x) //guaranteed to print 7
  }
samdoesnothing 4 days ago | parent | next [-]

Is that the case? I thought that it would be a copy instead of a heap allocation.

Of course the compiler could inline it or do something else but semantically its a copy.

masklinn 3 days ago | parent [-]

A copy of what? It’s returning a pointer, so i has to be on the heap[0].

gc could create i on the stack then copy it to the heap, but if you plug that code into godbolt you can see that it is not that dumb, it creates a heap allocation then writes the literal directly into that.

[0] unless Foo is inlined and the result does not escape the caller’s frame, then that can be done away with.

compsciphd 4 days ago | parent | prev [-]

ok, I'd agree with you in that example a go programmer would expect it to work fine, but a C programmer would not, but that's not the example the writer gave. I stand by my statement that the example the writer gave, C programmer would expect to work just fine.

simiones 4 days ago | parent [-]

I think the writer had multiple relatively weird confusions, to be fair. It's most likely that "a little knowledge is a dangerous thing". They obviously knew something about escape analysis and Go's ability to put variables on the stack, and they likely knew as well that Go slices are essentially (fat) pointers to arrays.

As the author shows in their explanations, they thought that the backing array for the slice gets allocated on the stack, but then the slice (which contains/represents a pointer to the stack-allocated array) gets returned. This is a somewhat weird set of assumptions to make (especially give that the actual array is allocated in a different function that we don't get to see, ReadFromFile, but apparently this is how the author thought through the code.