我有一个小程序,如下所示,它在结构中使用一个未初始化的字段。我用-Wuninitialized -Wmissing-field-initializers -Wall -Wextra -Werror (下面的Godbolt)编译程序,程序编译正常并运行,但在读取结构时打印未初始化的垃圾值。
在使用未初始化变量的情况下,有没有办法对这种编程错误发出警告?
#include <stdio.h>
enum FWPixelDepth {
FWPixelDepthColor8888,
};
struct FWBitmapDecodeOptions {
FWPixelDepth pixelDepth;
float scale;
bool decodeWithoutPremultiply;
};
static void p(FWBitmapDecodeOptions opts) {
printf("%d, %f, %d", opts.pixelDepth, opts.scale, opts.decodeWithoutPremultiply);
}
int main() {
FWBitmapDecodeOptions opts;
opts.decodeWithoutPremultiply = true;
p(opts);
}Clang 8.0.0标志:-O3 -Wuninitialized -Wmissing-field-initializers -Wall -Wextra -Werror
示例输出:
-1557482600, 0.000000, 1发布于 2020-09-30 07:32:57
与其他编程语言不同,在C++中,当使用带有POD type的变量时,通常无法在运行时检测该变量是否已初始化。为了检测到这一点,每个变量都需要一个相关的标志,用于指定变量是否已初始化。这将耗费大量的空间和性能。因此,这种运行时检查通常只由一些高级编程语言完成。
但是,在编译时,在可能的代码路径数量非常有限的简单情况下,编译器可能会检测到对未初始化数据的读访问。但这肯定是不可靠的,因为不能期望编译器总是能够检查所有可能的代码路径。
因此,为了检测对未初始化数据的读访问,最好使用特殊的调试工具,该工具在运行时检测此类错误,并为此牺牲性能。这类工具的示例是valgrind和Clang memory sanitizer。
https://stackoverflow.com/questions/64128809
复制相似问题