简体   繁体   中英

Memory corruption when using boost::shared_ptr in a multithreaded environment

* glibc detected * malloc(): memory corruption (fast): ***

This is the error I get when, in a multithreaded environment, I execute this portion of code:

/// Some declarations
typedef boost::shared_ptr<Object> ObjectPtr;

ObjectPtr getObject()
{
    return ObjectPtr(new Object);
}

/// What is actually executed in a thread
void executeWork()
{
    ...
    ObjectPtr object = getObject(); /* <--- Memory corruption here! */
    ...
}

Can you help me please?

I don't know if this helps your specific problem, but it is sometimes desirable to use make_shared and avoid the new .

so:

return boost::make_shared<Object>(/* any arguments to constructor here */);

Additionally, you could try std::shared_ptr instead of boost::shared_ptr . They're probably exactly the same, but maybe not? To use it via TR1, I believe you #include <tr1/memory> . I usually just use it via C++0x, in which case it's #include <memory> and add -std=c++0x to your g++ flags.

It's likely to be a problem with Object. What happens if you change Object to int?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM