wulfgarpro
wulfgarpro

Reputation: 6924

g++ dangling pointer warning inconsistency?

Is this the same thing?

1.

int* f() {
    int x = 5;
    return &x;
}

2.

int* f() {
    int x = 5;
    int* pX = &x;
    return pX;
}

g++ only returns a warning for 1., why not 2.?

Upvotes: 0

Views: 485

Answers (2)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158459

I can get gcc to warn on both by turning on optimization see it live:

warning: address of local variable 'x' returned [-Wreturn-local-addr]
 int x = 5;
     ^

 warning: function returns address of local variable [-Wreturn-local-addr]
 return pX;
        ^

These types of warnings can often be effected by the optimization level, gcc has a ten year old bug report on the inconsistency of the detecting use of a variable before initialization which varies greatly based on optimization level.

At the end of the day when you have undefined behavior the compiler is not obligated to provide a diagnostic and in fact many of the behaviors are designated as undefined as opposed to ill-formed because of the difficulty of consistently detecting them.

Upvotes: 3

R Sahu
R Sahu

Reputation: 206567

Is this the same thing?

Yes.

g++ only returns a warning for 1., why not 2.?

I don't know for sure but my guess is that the return statement is one step removed from taking the address of a local variable. The compiler doesn't necessarily know how pX was set by the time the return statement is executed.

int* f() {
    int x = 5;

    // There is no problem here.
    int* pX = &x;

    // The compiler doesn't care to find out how pX was set.
    // it could have been pX = malloc(sizeof(int))
    // It assumes that pX is a valid pointer to return.
    return pX;
}

Upvotes: 4

Related Questions