I'm investigating a memory leak issue that we have in our code. There is the following struct:
struct Config {
const uint32_t version = 1;
const uint32_t _sizeof = (5*sizeof(uint32_t));
uint32_t lengthOriginal;
uint32_t lengthCompressed;
uint32_t reserved = 0;
unsigned char buffer[1];
};
It is used with the unique_ptr
in the following manner:
static Config inited;
std::unique_ptr<Config> ptr;
ptr.reset(reinterpret_cast<Config *>(new char[1 + inited._sizeof + dataLength]));
memset(ptr.get(), 0, inited._sizeof + 100);
memcpy(ptr.get(), &inited, sizeof(inited));
And I'm pretty sure that the memory leak comes from mixing the unique_ptr
and the new
operator.
When running the Valgrind Memcheck, it warns about Mismatched free() / delete / delete []
, but it shows All heap blocks were freed -- no leaks are possible
.
On the other side, trying to run this code with overridden operator delete ( void* ptr, std::size_t sz )
, the size it tries to release is 24 bytes, which is much less than the allocated memory size.
Currently, I'm not sure if there is a memory leak here?
And if so, how to solve it? Possibly, passing a custom deleter to the unique pointer will solve this.
But, the other question is it a common practice to use memory allocation and smart pointers in that way?
The struct itself cannot be changed.