C / C ++中的垃圾值 [英] garbage values in C/C++

查看:413
本文介绍了C / C ++中的垃圾值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

未初始化的变量如何获取垃圾值?

Possible Duplicate:
How an uninitialised variable gets a garbage value?

如何在C和C ++中生成垃圾值?编译器是否使用一些随机数生成技术生成垃圾值?

How are garbage values generated in C and C++ ? Does the compiler use some random number generation technique for generating garbage values?

推荐答案

如果你的意思是未初始化变量的值,生成。它们只是在那个内存位置发生的垃圾。

If you mean the values of uninitialized variables, those aren't generated. They're just whatever garbage happened to be in that memory location.

int *foo = new int;
std::cout << *foo << std::endl;

新的指针指向内存中的某个地址。 RAM的位总是存在的;没有办法知道什么是存储在那里。如果它刚刚从操作系统请求,它很可能是0(操作系统将擦除内存块,出于安全原因之前)。如果它以前被程序使用,谁知道。

New returned a pointer to some address in memory. That bit of RAM has always existed; there is no way to know what was stored there before. If it was just requested from the OS, it'll likely be 0 (the OS will erase memory blocks before giving them out for security reasons). If it was previously used by your program, who knows.

实际上,使用未初始化变量的结果是未定义的。您可能会得到一个不可预测的号码,您的程序可能会崩溃,或更糟。

Actually, the results of using an uninitialized variable are undefined. You might get back an unpredictable number, your program may crash, or worse.

即使您知道它可以安全地在您的平台上运行上述操作,依赖于给出随机值。它将出现随机,但可能实际上是比你想要的更可预测和可控。此外,分布将无处近制服。

Even if you know that its safe to run the above on your platform, you shouldn't rely on that giving a random value. It will appear random, but is probably actually quite a bit more predictable and controllable than you'd like. Plus, the distribution will be nowhere near uniform.

这篇关于C / C ++中的垃圾值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆