nmr
nmr

Reputation: 16849

Is there a way to emit a warning for the use of this uninitialized variable?

I have a small program, below, which uses an uninitialized field in a struct. I compile the program with -Wuninitialized -Wmissing-field-initializers -Wall -Wextra -Werror (Godbolt link below), and the program compiles OK and runs, but prints uninitialized garbage values when reading the struct.

Is there a way to get a warning for this kind of programming error, where an uninitialized variable is used?

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

https://godbolt.org/z/cjc8cY

Clang 8.0.0 flags: -O3 -Wuninitialized -Wmissing-field-initializers -Wall -Wextra -Werror

Sample output:

-1557482600, 0.000000, 1

Upvotes: 4

Views: 632

Answers (1)

Andreas Wenzel
Andreas Wenzel

Reputation: 24846

In contrast to other programming languages, in C++, it is normally not possible to detect at run-time whether a variable with a POD type is initialized or not, when it is used. In order to detect this, every variable would need an associated flag which specifies whether the variable is initialized or not. This would cost a significant amount of space and performance. For this reason, such run-time checks are generally only done by some higher-level programming languages.

However, at compile-time, it may be possible for the compiler to detect read access to uninitialized data in simple cases, when there is a very limited number of possible code paths. But this is bound to be unreliable, as the compiler cannot be expected to always be able to check all possible code paths.

Therefore, in order to detect read access to uninitialized data, you are probably better off using a special debugging tool which detects such errors at run-time and sacrifices performance in order to do so. Examples of such tools are valgrind and the Clang memory sanitizer.

Upvotes: 3

Related Questions