开发者

glibc detected : free(): invalid pointer: with simple boost::ptr_map example

I know there are scores of questions with "* glibc detected * free(): invalid pointer", but the following is a minimalist example with boost::ptr_map:

#include <boost/ptr_container/ptr_map.hpp>
#include <string>

int main() {
        boost::ptr_map<std::string, int> map;
        int one = 1;
        int* pone = &one;
        string un = "one";
        map.insert(un, pone);
}

The code compiles, but at run time:

boost.library/ptr_container $ ./run.ptrmap
*** glibc detected *** ./run.ptrmap: free(): invalid pointer: 0x00007ffffd5c4578 ***
======= Backtrace: =========
/lib/libc.so.6[0x7fd5e99202f6]
/lib/libc.so.6(cfree+0x6c)[0x7fd5e9924c6c]
./run.ptrmap[0x401066]
/lib/libc.so.6(__libc_start_main+0xfd)[0x7fd5e98c8abd]
./run.ptrmap[0x400e79]
======= Memory map: ========开发者_JS百科
etc..

It's been repeated throughout SO that this kind of error is caused when trying to delete an invalid pointer. However, what changes in the above very simple code would avert this error?

The background of this question is that I am struggling to understand the proper usage of boost::ptr_map. Unfortunately, the official boost documentation is very sparse as far as ptr_map is concerned (no tutorial, no example with ptr_map). No boost::ptr_map tutorial seem to exist on the web. I have problems retrieving values, and accessing methods to the mapped classes I created. Thus, I tried to create the simplest example I could, but got off on a bad start as evidenced above.

Any help with the glibc error above and with ptr_map in general is appreciated. Thanks.

Edit: I have read over 20 times, studied and copied the examples from the official boost tutorial http://www.boost.org/doc/libs/1_46_0/libs/ptr_container/doc/tutorial.html As stated above, the boost tutorial barely covers ptr_map, so linking to it won't make any bit of difference. Basically, I have gone through and through the whole boost ptr container manual many times.


Tutorial: http://www.boost.org/doc/libs/1_39_0/libs/ptr_container/doc/tutorial.html (found by googling for: boost ptr_map)

ptr_map takes ownership of the pointers it's given, therefore it needs to be given heap allocated (new) objects. You've given it a pointer to a stack-allocated object, so when the ptr_map is cleaned up it tries to delete something that is on the stack.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜