Unitialized int value always the same (C++)

為{幸葍}努か 提交于 2021-02-16 20:31:27

问题


Given this code:

void main()
{
int x; 
cout << x;
system("pause");
}

When I debug this piece of code, it always prints -858993460A. I read that its because VS set this as default value for Unitialized vars. But I also read that in release mode, this should get random value. But everytime I run this code in release mode I get 1772893972A , which Is not changing -> its not random. What is this? Why do I get this value?


回答1:


The main is not the real entrypoint of the executable, in general the real entrypoint is taken by the runtime library (and in VC++ is definitely like that), which performs some CRT initialization tasks and then calls your main. That value is probably a leftover of one of the function calls performed by the initialization code; the difference between the Debug and Release builds is probably due to different initialization/stack management between the two configurations. By the way, it's just a chance that such vales are always the same, probably they are from some parameter/variable that assumes the same value every time.

If it's not like that, it's probably stuff from some other initialization task internal to your process. It's not stuff from other processes or that just "happened" to be at that spot in physical memory, since Windows (on which your application is running) never gives memory pages that belonged to other processes without first blanking them.

Still, keep in mind that, as far as the standard is concerned, uninitialized variables have "indeterminate initial value" (§3.3.1 ¶9), so you should not rely on the values you may get by reading uninitialized variables. If you need random numbers, use the appropriate library functions.


I was forgetting... void main is not valid C++, it should be int main (§3.6.1 ¶2, "It shall have a return type of type int").




回答2:


Your confusion is in the assumption that "in release mode, this should get a random value." That is not true.

An uninitialized variable gets an "undefined" value. It could be random, but it doesn't have to be.

If you want x to have a random value, then use rand().




回答3:


Interestingly, your DEBUG value in hex is 0xFFFFFFFFCCCCCCCC. Your RELEASE value in hex is just random. It could be that the debug compile adds a stack scribbler to make sure your uninitialized values are not sane (like 0) and would be quickly noticeable.



来源:https://stackoverflow.com/questions/5568997/unitialized-int-value-always-the-same-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!