0

Okay so I have this program of mine:

#include <unistd.h>
#include <stdio.h>
int deCode(int x[2][5])
{
    return x[2][4]; // Heres where the "garbage" comes in.
}    //     calling x[2][4] is non valued function. I can call [0,1][0,1,2,3,4]

int main(void)
{
    int newPosition;
    int x[2][5]={
                {1,3,5,7,9}, //[0][0-4] // row 0
                {2,4,6,8,10} //[1][0-4] // row 1
                };                      //NOTICE NO ROW 2
    printf("%d\n", deCode(&x));
}

I got value 1 when I play this program. Obviously you probably wont get the same resolut. when i do [2][1,2,3,5] I get true garbage. Im just wondering is that like one in a million chance or am I missing something?

mmmmmm
  • 32,227
  • 27
  • 88
  • 117

1 Answers1

4

It's definitely not random. It's undefined.

For instance, you may just be reading another variable. If that variable were the the character array \0\0\0\0\0... you would be reading a lot of zeros. If it were the int array 1, 1, 1, 1... you would read 1's.

Very often you'll see numbers like 2^32-1, which you may be quick to recognize. Things like that happen when you accidentally interpret a signed int as an unsigned int.

One strategy in debugging is to initialize all memory to 0xCC. Then you will not receive raw memory, you will see 0xCC, which has a very good chance of crashing your program instead of being silently accepted.

Community
  • 1
  • 1
djechlin
  • 59,258
  • 35
  • 162
  • 290
  • 1
    Indeterminate is a good word — the values are indeterminate but not random in the sense of a good PRNG. Not that undefined is wrong; the values are not defined by the standard. And the code invokes undefined behaviour by accessing memory outside the bounds of the array it is passed. – Jonathan Leffler Feb 09 '14 at 16:49