0

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.?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
wulfgarpro
  • 6,666
  • 12
  • 69
  • 110
  • They are slightly different, in the first example `x` will be destroyed on function return. In the second one, address of `x `is already stored in `pX`, so destruction of `x` does not delete the value stored in `pX`, which you can return like a simple integer value. – Sept Oct 19 '15 at 03:25
  • @Alparslan: So pX keeps x on the stack? – wulfgarpro Oct 19 '15 at 03:27
  • No, it doesn't force X to be kept on stack, but it simple keeps the old address of X as a separate integer and you can return that even after X is destroyed. – Sept Oct 19 '15 at 03:28
  • @Alparslan: so 2. still has the same memory implications as 1.? That is, there is the possibility of 2. pointer to an inconsistent value? – wulfgarpro Oct 19 '15 at 03:30
  • 1
    Exactly, in both cases, the returned memory address will be invalid. And you can crash your program if you try to write on the returned address in both cases. – Sept Oct 19 '15 at 03:31

2 Answers2

4

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;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
3

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.

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740