2

I had a hard time to find a bug in my code caused by a loop like this:

for (int i=i;i<5;i++){
    // ...
}

I use g++ 4.7.2 with -O2 -Wall, but no warning/error is shown. Is there some compiler flag that also in combination with -O2 creates a warning for such a case?

I found several related questions: here in the comments it is discussed, that g++ shows a warning with -Wall when there is no -O2. However, that question is particular because the problematic loop is optimized away with -O2 which would explain that no warning is shown. In my case the loop is not optimized away, but still I get no warning. Also related is this question and this one. After reading those questions, I understand why c++ allows such non-sense (I like the example here because it isnt nonsense at all), but I am still looking for a compiler flag that would create a warning also with -O2.

Community
  • 1
  • 1
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • Upvoting question because it made me realize my gcc has the same problem and I should use a more recent one. – jdarthenay Apr 08 '16 at 11:11

1 Answers1

1

The clang compiler gives me, when compiling

int main()
{
    int j = 0;
    for (int i=i; i<5; ++i)
        j++;
    return 0;
}

with -O2 -Wall:

warning_loop.cxx:4:16: warning: variable 'i' is uninitialized 
when used within its own initialization [-Wuninitialized]
 for (int i=i; i<5; ++i)

The gcc (version 5.3) compiler gives a warning as well:

warning_loop.cxx: In function 'int main()':
warning_loop.cxx:4:16: warning: 'i' is used uninitialized in 
this function [-Wuninitialized]
 for (int i=i; i<5; ++i)

The usage of uninitialized values can be traced with valgrind

valgrind --track-origins=yes ./a.out

To give output:

==33052== Memcheck, a memory error detector
==33052== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==33052== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==33052== Command: ./a.out
==33052== 
==33052== Conditional jump or move depends on uninitialised value(s)
==33052==    at 0x100000F8C: ??? (in ./a.out)
==33052==    by 0x10022F5AC: start (in /usr/lib/system/libdyld.dylib)
==33052==  Uninitialised value was created by a stack allocation
==33052==    at 0x7FFF5FC01036: _dyld_start (in /usr/lib/dyld)
Chiel
  • 6,006
  • 2
  • 32
  • 57