Pointers and Local Variables

A common programming error is to return a pointer to a local variable from a function, e.g:

This is illegal because the local variable is destroyed when the function returns.

struct a *f(..) {
    struct a x;
    ....
    return &x; /* bad */
}

char *f(..) {
    char a[10];
    ....
    return &a; /* bad */
}

gcc warns about this when its done directly.

Program behaviour will be unpredictable.

Index