logoalt Hacker News

foldrlast Thursday at 5:21 PM1 replyview on HN

What confuses people is

    int *foo(void) {
        int x = 99;
        return &x; // bad idea
    }
vs.

    func foo() *int {
        x := 99
        return &x // fine
    }
They think that Go, like C, will allocate x on the stack, and that returning a pointer to the value will therefore be invalid.

(Pedants: I'm aware that the official distinction in C is between automatic and non-automatic storage.)


Replies

knorkerlast Thursday at 9:33 PM

Yes. That's escape analysis. But this is not what OP did.

What you wrote is not the same in C and Go, because GC and escape analysis. But 9rx is also correct that what OP wrote is the same in C and Go.

So OP almost learned about escape analysis, but their example didn't actually do it. So double confusion on their side.

show 1 reply