1

Why does valgrind reports on uninitialised bytes in the following code?

#include <valgrind/memcheck.h>

class Test {
public:
    Test() {}
};

int main(int argc, char* argv[]) {
    Test a;
    VALGRIND_CHECK_VALUE_IS_DEFINED(a);
    return 0;
}

If I add a member variable to test and initialise it, there is no output.

1 Answer 1

4

In your example, the size of 'a' will be 1:

printf("%ld\n",sizeof(a)); => 1

sizeof() only reports the data in a class, but since each unique class must have it's own address, a padding byte is added. The reason valgrind complains is that you are accessing the padding byte, which the compiler has no obligation to initialize to any value.

See here for a comment on why the minimum size of a class is 1 and not 0.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.