鉴于此代码:
void main() { int x; cout << x; system("pause"); }当我调试这段代码时,它总是打印-858993460A。 我读到它是因为VS将此设置为Unitialized vars的默认值。 但我也读到,在发布模式下,这应该是随机值。 但每次我在发布模式下运行此代码时,我都会得到1772893972A ,这不会改变 - >它不是随机的。 这是什么? 为什么我得到这个价值?
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?
最满意答案
main不是可执行文件的真正入口点,一般来说,真正的入口点是由运行时库(在VC ++中就是这样),它执行一些CRT初始化任务,然后调用你的main 。 该值可能是初始化代码执行的函数调用之一的剩余部分; Debug和Release版本之间的区别可能是由于两种配置之间的初始化/堆栈管理不同。 顺便说一句,这样的值很可能总是相同的,可能它们来自某个参数/变量,它每次都假设相同的值。
如果它不是那样的话,它可能来自你进程内部的一些其他初始化任务。 它不是来自其他进程的东西,或者只是“碰巧”出现在物理内存中的那个位置,因为Windows(运行应用程序的程序)从未提供属于其他进程的内存页面而不先消隐它们。
但是,请记住,就标准而言,未初始化的变量具有“ 不确定的初始值 ”(§3.3.1¶9),因此您不应该依赖于通过读取未初始化的变量而获得的值。 如果需要随机数,请使用适当的库函数。
我忘了... void main不是有效的C ++,它应该是int main (§3.6.1¶2, “它应该有一个int类型的返回类型” )。
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").
更多推荐
发布评论