Tuesday, January 4, 2022

[SOLVED] Unexpected Behaviour on calling simple C function

Issue

On Running following c code the output is neither 0 nor a constant number and even after trying to use some print statements in random block, i can't not conclude what's happening

#include <stdio.h>

int random(int start, int end); // start, end are just added to make sure that results are not same due to caching.

int main(void) {
    int i;
    for (i=0; i<10; i++)
        printf("%d\n", random(0, i));

    return 0;
}

int random(int start, int end) {
    int out_num;
    return out_num;
}

$ gcc -o ./compiled/bogo_binary_search bogo_binary_search.c && ./compiled/bogo_binary_search 
0
32653
32653
32653
32653
32653
32653
32653
32653
32653

Solution

An uninitialized variable has an indeterminate value. That only means that the standard does not say what the value should be. The compiler could use a fixed value or a random one if it wants. What it most often does in practice is to use whatever was in memory without setting it. So in one sense it is random, because it's not completely predictable.

But as a random generator it is very poor. Some values are way more possible than others. All zeros is extremely common. And if you run the program many times in a row on one machine, it's quite likely that whatever value you got will be the same next time.

And of course, it's undefined behavior to read an uninitialized variable, so i theory, the compiler could do anything. But it's very likely it will just print the value, whatever it is.



Answered By - klutt