Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this valid C? No warning about p being uninitialized

Tags:

c

gcc

Compiling this code snippet with gcc (4.5) and as many -Wall, -Wextra, -Wuninitialized type flags turned on as possible gives me no warnings:

int main() {
    int *p = p;
    printf("p = %p\n", (void *)p);
    return 0;
}

But running it multiple times gives this output:

p = 0xbe9ff4
p = 0x550ff4
p = 0xeb1ff4
p = 0x4caff4

... and so on.

What's going on here?

EDIT: Compiling with "g++ -Wall" instead gives me warning as I'd expect:

In function ‘int main()’: warning: ‘p’ is used uninitialized in this function
like image 569
akent Avatar asked Jul 13 '11 08:07

akent


2 Answers

int *p = p;

p is defined as soon as int *p is parsed, but the RHS is only evaluated afterwards. This statement is equivalent to

int * p;
p = p;

This is different in C++ with implicit constructors, but in plain ol' C, this is what you have. Undefined initial value.

As far as the compiler warning goes, it's a Quality Of Implementation issue. gcc isn't being "tricked", it's just being permissive.

like image 61
spraff Avatar answered Nov 19 '22 06:11

spraff


Valgrind gives warnings about p being uninitialized. I guess that gcc is tricked and a bug report should be filled in.

like image 28
Mihai Maruseac Avatar answered Nov 19 '22 06:11

Mihai Maruseac