简体   繁体   English

调用简单 C function 时出现意外行为

[英]Unexpected Behaviour on calling simple C function

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在按照 c 代码运行时,output 既不是 0 也不是常数,即使在尝试在随机块中使用一些打印语句之后,我也不能断定发生了什么

#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
int random(int start, int end) {
    int out_num;
    return out_num;
}

The local variable out_num is uninitialized .局部变量out_num未初始化 It could have any value, or your program could crash when you try to use it.它可能有任何价值,或者当您尝试使用它时您的程序可能会崩溃。

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.它在实践中最常做的是使用 memory 中的任何内容而不进行设置。 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.但它很可能只会打印该值,无论它是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM