logoalt Hacker News

compsciphdlast Thursday at 2:41 PM1 replyview on HN

I don't see how this is coming at go "from below".

even in C, the concept of returning a pointer to a stack allocated variable is explicitly considered undefined behavior (not illegal, explicitly undefined by the standard, and yes that means unsafe to use). It be one thing if the the standard disallowed it.

but that's only because the memory location pointed to by the pointer will be unknown (even perhaps immediately). the returning of the variable's value itself worked fine. In fact, one can return a stack allocated struct just fine.

TLDR: I don't see what the difference between returning a stack allocated struct in C and a stack allocated slice in Go is to a C programmer. (my guess is that the C programmer thinks that a stack allocated slice in Go is a pointer to a slice, when it isn't, it's a "struct" that wraps a pointer)


Replies

simioneslast Thursday at 2:52 PM

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
  }
show 2 replies