Reputation: 47
I created this small piece of software in C:
#include <stdio.h>
#include <stdlib.h>
void print_this_list(int size){
int list[size];
for (int i = 0; i < size; i++) {
printf("%d\n", list[i]);
}
}
int main(int argc, char *argv[]){
print_this_list(25);
return 0;
}
The results of the execution are very interesting (apparently) random numbers:
-1519340623
859152199
-1231562870
-1980115833
-1061748797
1291895270
1606416552
32767
15
0
1
0
104
1
1606578608
32767
1606416304
32767
1606423158
32767
1606416336
32767
1606416336
32767
1
Program ended with exit code: 0
What exactly are those numbers and what is the "logic" behind them?
Upvotes: 0
Views: 103
Reputation: 16607
No logic behind them .It's Undefined Behaviour
void print_this_list(int size){
int list[size]; // not initialized
for (int i = 0; i < size; i++) {
printf("%d\n", list[i]); // still you access it and print it
}
}
list
is uninitialized and you print it's contents (which are indeterminate) .Therefore ,you get some random garbage values as output.
In order to get working you need to initialize it . You can try this -
void print_this_list(int size){
int list[size];
for (int i = 0; i < size; i++) {
list[i]=i; // storing value of i in it before printing
printf("%d\n", list[i]);
}
}
Upvotes: 9
Reputation: 1
it's trash . uninitialized value
if you try
int x; // i define x as uninitialized variable some where in the memory (non empty)
printf("%d",x); // will print trash "unexpected value
// if i do this
int x=10;//i define x with initial value so i write over the trash was found in this block of the memory .
and if i print out of range index as
int ar[10];
for(int i=0;i<10;i++)
ar[i]=rand();
printf("%d\n",ar[10]);//out of index uninitialized index it will print trash .
i hope that's help
Upvotes: 0