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

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

问题描述

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

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

我期望 uninitialized.b 是不可预测的随机性;显然一个bug和容易
发现如果优化和警告打开。但是编译只有-g,没有
警告。一个同事有一个案例,类似于这样的代码工作,因为
巧合有一个有效的值;当编译器升级时,它开始失败。
他认为这是因为新编译器在结构
中插入已知的值(VS填充0xCC的方式)。在我自己的经验中,只是不同的
随机值,并不是有效的。



但现在我很好奇 - 设置g ++,这将使它填补
内存,否则标准会说明应该未初始化?

解决方案

例如,所有全局(和静态)变量都驻留在 .bss 中, / code>节,它总是初始化为零。但是,为了兼容性,未初始化的部分放在 .bss 中的特殊部分。



要将它们归零,可以将 -fno-common 参数传递给编译器。或者,如果您需要在每个变量的基础上,使用 __ attribute__((nocommon))



堆,可以编写自己的分配器来完成你所描述的。但对于堆栈,我不认为有一个容易的解决方案。


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);
}

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.

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?

解决方案

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

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.

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天全站免登陆