-8
using namespace std;
struct s{
    int tab[9]; 
};

int main(){
    s x;

EDITION the same output I've got after initialization

(x.tab)[0]=1;
(x.tab)[1]=1;
(x.tab)[2]=1;
(x.tab)[3]=1;
(x.tab)[4]=1;
(x.tab)[5]=1;
(x.tab)[6]=1;
(x.tab)[7]=1;
(x.tab)[8]=1;

    cout<<(x.tab[0]);
}

How does the code above produce the output below? Is it interpretable or is it undefined behaviour - nasal demon? I think the second one, because the size of the output matrix is independent from the size of tab array.

2293236 2293240 2293244 2293248 2293252 2293256 2293260 2293264 2293268
2293272 2293276 2293280 2293284 2293288 2293292 2293296 2293300 2293304
2293308 2293312 2293316 2293320 2293324 2293328 2293332 2293336 2293340
2293344 2293348 2293352 2293356 2293360 2293364 2293368 2293372 2293376
2293380 2293384 2293388 2293392 2293396 2293400 2293404 2293408 2293412
2293416 2293420 2293424 2293428 2293432 2293436 2293440 2293444 2293448
2293452 2293456 2293460 2293464 2293468 2293472 2293476 2293480 2293484
2293488 2293492 2293496 2293500 2293504 2293508 2293512 2293516 2293520
2293524 2293528 2293532 2293536 2293540 2293544 2293548 2293552 2293556

--------------------------------
Process exited with return value 0
Press any key to continue . . .
Qbik
  • 5,885
  • 14
  • 62
  • 93

1 Answers1

6

Using an uninitialized variable ivokes UB. You have not initialized x so yes, you are invoking undefined behavior.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
  • 1
    Pretty sure it's not undefined behavior; the location just has an "unspecified value". Meaning you can't rely on the value, and it's a bad idea in any case (i'd have thought the compiler would even warn about it), but nothing will catch fire and no demons will fly out of anyone's nose. – cHao Mar 11 '13 at 20:53
  • @cHao http://stackoverflow.com/questions/1597405/what-happens-to-a-declared-uninitialized-variable-in-c-does-it-have-a-value for instance – Ivaylo Strandjev Mar 11 '13 at 20:55
  • Well, that's enlightening. :) The assumptions one makes when they've worked with full-sized, two's-complement integral types all their life...lol... +1 – cHao Mar 11 '13 at 21:06
  • I don't get it at all, why this is UB? Why you are saying he isn't initializing the x's i mean am i dump? or isn't `x.tab=X;` a initialization since x is not a pointer and tab also isnt, its a bounded array isntead. Sp how he's getting so many different outputs by just a single cout? and Why this isn't declared? And at all. i dont even get it where there is UB?! – dhein Aug 12 '13 at 09:50