'Why is double free called in this situation?
I've come about with the following situation that I fortunately solved by refactoring some other code, not related to the actual issue which I managed to capture below.
The code:
#include <boost/asio.hpp>
void passIocPtr(__attribute__((unused)) std::shared_ptr<boost::asio::io_context> iocPtr)
{}
void makeptr(boost::asio::io_context* ioc)
{
std::shared_ptr<boost::asio::io_context> iocPtr = std::make_shared<boost::asio::io_context>();
iocPtr.reset(ioc);
passIocPtr(iocPtr);
}
void makeptr2(boost::asio::io_context* ioc)
{
std::shared_ptr<boost::asio::io_context> iocPtr(ioc);
passIocPtr(iocPtr);
}
int main()
{
boost::asio::io_context ioc;
// makeptr(ioc);
makeptr2(ioc);
}
Both functions (makeptr and makeptr2) would result in:
double free or corruption (out) / free(): invalid pointer
The code I was working on had to use a pointer to a io_context. Not entirely sure if the issue I had is specifically related to the ioc, I think it's pretty much my bad usage of smart pointers.
Maybe someone can give me some insight on how I should approach this better.
Solution 1:[1]
shared_ptr is exclusively for managing heap objects
here:
int main()
{
boost::asio::io_context ioc;
// makeptr(ioc);
makeptr2(ioc);
}
you are passing a stack object to shared_ptr (eventually in make_ptr2). All bets are off after that. The double free message really means 'whoa - you have trashed your heap'
If you want this to work put ioc on the heap
int main()
{
boost::asio::io_context *ioc = new boost::asio::io_context;
// makeptr(ioc);
makeptr2(ioc);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pm100 |
