Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Not being a experienced C programmer by any measure, but this doesn't look right to me: https://github.com/thraxil/boggle/blob/master/boggle.c#L92

    struct foo f() {
        struct foo f;
        return f;
    }
isn't returning a stack-allocated struct a bad idea?


It returns a copy of it. Example:

#include <stdio.h>

struct foo { char space[1024]; };

struct foo f()

{

    struct foo f;

    printf("address of f is %p\n",&f);

    return f;
}

int main()

{

    struct foo g;

    g = f();

    printf("address of g is %p\n",&g);

    return 0;
}

produces this output:

address of f is 0x7fbfffec30

address of g is 0x7fbffff050


If I remember correctly (been a long time), most compilers would implement many cases of struct return by letting the caller pass the address of a block of (stack) memory to contain the return value. The function can then optimize things to get rid of its local copy, operate directly on the intended target, and the caller doesn't need to perform any copies.


Thanks, I didn't know that.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: