logoalt Hacker News

wrstoday at 1:30 AM2 repliesview on HN

Exactly as well as C does, it seems.

    func newPerson() *Person {
        p := Person{Name: "Alice", Age: 30}
        return &p
    }
becomes

    static main_Person* newPerson(void) {
        main_Person p = (main_Person){.Name = so_str("Alice"), .Age = 30};
        return &p;
    }
Quoting the FAQ: "So itself has few safeguards other than the default Go type checking. It will panic on out-of-bounds array access, but it won't stop you from returning a dangling pointer or forgetting to free allocated memory. Most memory-related problems can be caught with AddressSanitizer in modern compilers, so I recommend enabling it during development by adding -fsanitize=address to your CFLAGS."

So saying you get the "safety of Go" is a bit of a stretch.


Replies

nvme0n1p1today at 2:31 AM

Yeah that's not great. It's easy to be faster than go if you haven't thought about memory management yet. I bet go with GOGC=off is faster than plain go too.

nixon_why69today at 6:56 AM

That's undefined behavior in C I thought? You're addressing the memory of a stack frame that already collapsed when it returned. I think it's ok for compilers to either segfault or work like you'd think they would for that example in C.

You can pass pointers to earlier frames in the stack, they're still active, but you can't return a pointer to an expired stack frame.

show 1 reply