g ++可以用已知值填充未初始化的POD变量吗? [英] Can g++ fill uninitialized POD variables with known values?

查看:12
本文介绍了g ++可以用已知值填充未初始化的POD变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道调试选项下的 Visual Studio 将使用已知值填充内存.g++(任何版本,但 gcc 4.1.2 最有趣)是否有任何选项可以用可识别的值填充未初始化的本地 POD 结构?

I know that Visual Studio under debugging options will fill memory with a known value. Does g++ (any version, but gcc 4.1.2 is most interesting) have any options that would fill an uninitialized local POD structure with recognizable values?

struct something{ int a; int b; };
void foo() {
    something uninitialized;
    bar(uninitialized.b);
}

我希望 uninitialized.b 是不可预知的随机性;显然是一个错误并且很容易发现优化和警告是否打开.但是只用 -g 编译,没有警告.一位同事有一个案例,其中与此类似的代码有效,因为它巧合地有一个有效值;当编译器升级时,它开始失败.他认为这是因为新编译器将已知值插入到结构中(很像 VS 填充 0xCC 的方式).根据我自己的经验,它只是不同碰巧无效的随机值.

I expect uninitialized.b to be unpredictable randomness; clearly a bug and easily found if optimization and warnings are turned on. But compiled with -g only, no warning. A colleague had a case where code similar to this worked because it coincidentally had a valid value; when the compiler upgraded, it started failing. He thought it was because the new compiler was inserting known values into the structure (much the way that VS fills 0xCC). In my own experience, it was just different random values that didn't happen to be valid.

但现在我很好奇 - 是否有任何 g++ 设置可以让它填充否则标准会说应该未初始化的内存?

But now I'm curious -- is there any setting of g++ that would make it fill memory that the standard would otherwise say should be uninitialized?

推荐答案

我认为 gcc/g++ 中不存在这样的选项/功能.

I don't think such option/feature exists in gcc/g++.

例如,所有全局(和静态)变量都位于 .bss 部分中,该部分始终初始化为零.但是,为了兼容性,未初始化的会放在 .bss 中的特殊部分中.

For instance, all global (and static) variables reside in the .bss section, which is always initialised to zeroes. However, uninitialised ones are put in a special section within the .bss, for sake of compatibility.

如果您希望它们也归零,您可以将 -fno-common 参数传递给编译器.或者,如果您需要基于每个变量,请使用 __attribute__ ((nocommon)).

If you want the them to be zeroed too, you can pass -fno-common argument to the compiler. Or, if you need it on a per-variable basis, use __attribute__ ((nocommon)).

对于堆,可以编写自己的分配器来完成您所描述的.但是对于堆栈,我认为没有一个简单的解决方案.

For heap, it's possible to write your own allocator to accomplish what you described. But for stack, I don't think there's an easy solution.

这篇关于g ++可以用已知值填充未初始化的POD变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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