Search code examples
c++c++17shared-ptrsmart-pointers

Raw pointer to shared_ptr bug


I'm working on a image treating application.

In summary, I have a byte buffer which stores the image data, so I can use this array to handle the image easily in wx widgets and OpenCV. I planned to store this byte buffer in a shared_ptr as it will be used in other instances of the same class along the execution.

With raw pointer it works properly, but whenever I tried to use shared_ptr I'm having an segmentation fault whenever passing this pointer to a function.

How can I pass it to this function without segmentation fault? it doesn't make sense to me this crashing

The bug is here

_dataSize = (size_t)len;
_originalData = std::make_shared<void*>(malloc(_dataSize));
if ( file.Read(_originalData.get(), _dataSize) != len )

on the last line of above code, I'm trying to pass the _original data pointer to Read function

Here's the full code, on the piece above, I just put the line that the bug is happening. On the full the code the bug is on src/Img.cpp file on line 18

Thank you


Solution

  • _originalData.get() is a void**, not a void*.

    To share ownership of that allocation, you need std::shared_ptr<void>, not std::shared_ptr<void*>. You also need to set the deallocation function, as it is undefined behaviour to delete a pointer that was malloced.

    _originalData = std::shared_ptr<void>{ malloc(len), free }; // _originalData is a `std::shared_ptr<void>
    if ( file.Read(_originalData.get(), len) != len )
    

    Alternatively, since C++20, you could use a std::shared_ptr<char[]>, and not use malloc at all.

    _originalData = std::make_shared_for_overwrite<char[]>{ len }; // _originalData is a `std::shared_ptr<char[]>
    if ( file.Read(*_originalData, len) != len ) // implicit conversion of char* to void*