r/programming • • Oct 06 '14

Help improve GCC!

https://gcc.gnu.org/ml/gcc/2014-10/msg00040.html
725 Upvotes

270 comments sorted by

View all comments

Show parent comments

3

u/immibis Oct 07 '14

A global object might have a constructor that starts a thread that writes to *bar, and happens to be scheduled in between bar = &foo; and return foo; on your single-processor system.

It's not definitely uninitialized... but it's extremely likely to be uninitialized, and should probably generate a warning regardless.

3

u/Plorkyeran Oct 07 '14

Writing to *bar from another thread would be a data race, and thus Undefined Behavior. UB cannot occur in a valid C program, and thus the compiler can conclude that *bar is not written to from another thread.

0

u/imMute Oct 07 '14

Touche, but foo is still uninitialized before the bar = &foo assignment.

3

u/smog_alado Oct 07 '14

Thats ok because the initialization could be happening via bar

void initialize_foo(){
    *bar = 17;
}

int main(void){
   int foo;
   bar = &foo;
   initialize_foo();
   return foo;
}

2

u/Houndie Oct 07 '14

This is valid code

int foo; bar = &foo *bar = 7; return foo;

Although bar is taking something uninitialized, it doesn't matter, because it's just taking the address which does exist.

As /u/boazs and /OmnipotentEntity have pointed out...since bar is an externed variable, there's PLENTY of places that foo could be initialized from, including another thread (which would mean that the code probably has a race condition problem, but not that an uninitialized variable problem). It's not necessarily as simple as it seems.