سؤال

I get a segmentation fault at this point of code when calling auto_ptr release member:

try
{
    newMod->init(params);
}
catch (const std::exception& e)
{
#ifndef CONFIG_STATIC
    dlclose(handle);
#endif
    throw std::runtime_error(utils::buildString(
            "%s: Error initializing module %s: %s",
            DBG_FUNC_NAME, newMod->name().c_str(), e.what()));
}

_modules.insert(std::make_pair(newMod->name(), newMod.release()));

Where _modules is

std::map<std::string, IModule*> _modules;

and newMod is

std::auto_ptr<IModule> newMod(0);

later reset with a proper pointer value. I know the pointer to IModule is valid, because I'm calling the init member before release.

This:

_modules.insert(std::make_pair(newMod->name(), newMod.get()));
newMod.release();

works perfectly well and this is what gdb says:

#0  _M_rep (this=0xbfe8e908, __str=...) at /usr/src/debug/gcc-4.5.1-20101208/obj-i586-suse-linux/i586-suse-linux/libstdc++-v3/include/bits/basic_string.h:287
#1  std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string (this=0xbfe8e908, __str=...)
at /usr/src/debug/gcc-4.5.1-20101208/obj-i586-suse-linux/i586-suse-linux/libstdc++-v3/include/bits/basic_string.tcc:173
#2  0x0805d76f in sm::core::mod::ModuleManager::loadModule (this=0x8074768, name=..., params=...) at src/core/ModuleManager.cpp:150
#3  0x08056edb in sm::core::Main::start (this=0xbfe8e9e0) at src/core/Main.cpp:82
#4  0x08055131 in main (argc=4, argv=0xbfe8ebf4) at src/core/smmain.cpp:15

and the line it segfaults on is:

{ return &((reinterpret_cast<_Rep*> (_M_data()))[-1]); }

Any idea on what could be wrong in this one?

هل كانت مفيدة؟

المحلول

_modules.insert(std::make_pair(newMod->name(), newMod.release()));

The order of evaluation of arguments to a function is not defined by the standard. An implementation can evaluate newMod.release() before newMod->name(), which would make that second call invalid.


Side note: auto_ptr is deprecated in C++11 (Annex D.10 in draft n3290):

The class template auto_ptr is deprecated. [ Note: The class template unique_ptr (20.7.1) provides a better solution. — end note ]

If you have access to that, and the time/resource to do so, consider switch to the newer smart pointer classes.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top