Unitialized int值始终相同(C ++)(Unitialized int value always the same (C++))

编程入门 行业动态 更新时间:2024-10-20 07:49:29
Unitialized int值始终相同(C ++)(Unitialized int value always the same (C++))

鉴于此代码:

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").

更多推荐

本文发布于:2023-04-29 03:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1334530.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Unitialized   int

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!