Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can compilers give warnings when using uninitialised values?

Tags:

c

gcc

warnings

So let's say I'm careless and make a stupid typo.. this file:

test.c

#include <stdio.h>

int main()
{
    int x = x;
    printf("%d\n",x);
}

compiles fine:

mymachine:~ oll$ gcc test.c 
mymachine:~ oll$ ./a.out 
1782198366

Obviously int x = x is a mistake but the compiler accepts this without warning. I've wasted quite a few hours trying to this error.

Is there a compiler flag that and can use for gcc / g++ to make the compiler give me a warning when I use an uninitialised stack variable? This could potentially save me a lot of time in the future.

I have tried gcc -O -Wuninitialized test.c - didn't work.

Thanks in advance

Edit: I have tried -Wall, no mention of x

mymachine:~ oll$ gcc -Wall test.c 
test.c: In function ‘main’:
test.c:7: warning: control reaches end of non-void function

Edit: Solution found

It seems that using the command line tools gcc and g++ in OS X 10.8 doesn't give this warning, using clang works:

mymachine:~ oll$ clang -Wall test.c
test.c:5:10: warning: variable 'x' is uninitialized when used within its own initialization [-Wuninitialized]
        int x = x;
        ~   ^
1 warning generated.
like image 200
OLL Avatar asked Apr 09 '14 13:04

OLL


1 Answers

It looks like the warning flags you want are -Wuninitialized -Winit-self (see it live):

Warn about uninitialized variables that are initialized with themselves. Note this option can only be used with the -Wuninitialized option.

For example, GCC warns about i being uninitialized in the following snippet only when -Winit-self has been specified:

int f()
{
    int i = i;
    return i;
}

This warning is enabled by -Wall in C++.

Based on the comments below there may be some version dependencies. Note, that clang generates a warning for this just using -Wall, which seems more sensible to me:

warning: variable 'x' is uninitialized when used within its own initialization [-Wuninitialized]
int x = x;
    ~   ^

The live example I linked above also includes a commented out clang command line.

Also see Why is -Winit-self separate from -Wuninitialized.

like image 79
Shafik Yaghmour Avatar answered Nov 12 '22 17:11

Shafik Yaghmour