I try to debug a problem where Valgrind prints uninitialized value errors when using a boost::make_optional in connection with google mock. I tried to simulate the situation with a test app usign memcmp:
#include <string>
#include <boost/optional.hpp>
#include <stdio.h>
#include <cstring>
void testFunction( boost::optional< int > const cacheKey = boost::make_optional ( true, int() ) )
{
boost::optional< int > const cacheKey2 = boost::make_optional ( true, int() );
if ( memcmp ( &cacheKey, &cacheKey2, sizeof ( cacheKey2 ) ) )
{
printf ( "Equal\n" );
}
}
int main(int ac, char** av)
{
testFunction();
}
g++ -std=c++11 -g -O0 -o optionaltest optionaltest.cpp
valgrind --tool=memcheck --track-origins=yes ./optionaltest
==16255== Memcheck, a memory error detector
==16255== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==16255== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==16255== Command: ./optionaltest
==16255==
==16255== Conditional jump or move depends on uninitialised value(s)
==16255== at 0x4C35D72: __memcmp_sse4_1 (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==16255== by 0x1088F9: testFunction(boost::optional<int>) (optionaltest.cpp:11)
==16255== by 0x108995: main (optionaltest.cpp:20)
==16255== Uninitialised value was created by a stack allocation
==16255== at 0x1088BA: testFunction(boost::optional<int>) (optionaltest.cpp:8)
Is there a way to initialize the optional so that there are no uninitialized bytes inside it?
Regards
Edit: I gave both variables a make_optional now. Same error.
Edit 2: Creating a temporary std::optional, nulling it out with memset, then assigning it the value of the original and keep working with the temporary seems to work. It seems to be uninitialized memory in optional_aligned_storage.hpp. I wonder if there is a more elegant solution though.