boost::program_options导致malloc错误

6
我有一个玩具程序,在OSX 10.6上使用MacPorts gcc时会出现错误。
#include <boost/program_options.hpp>
namespace po = boost::program_options;

#include <iostream>
using namespace std;

int main(int ac, char* av[])
{
        po::options_description desc("Allowed options");
        desc.add_options()  ("help", "produce help message")  ;

        po::variables_map vm;        
        po::store(po::parse_command_line(ac, av, desc), vm);
        po::notify(vm);    

        if (vm.count("help")) {
            cout << desc << "\n";
            return 0;
        }
        cout << "Program continues\n";
        return 0;
}

我已经使用MacPorts安装了Boost 1.52版本。我将程序编译为:
g++ a.cpp -lboost_program_options-mt -L/opt/local/lib -g -O0

编译没有问题:

$ ./a.out
Program continues

但它无法打印帮助信息:
$ ./a.out --help
Allowed options:
a.out(40110) malloc: *** error for object 0x7fff70ca3500: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap

我听说如果库文件使用的gcc版本与程序构建时所用的版本不同,就会发生这样的情况。如何检查这个问题呢?

$ g++ --version
g++ (MacPorts gcc47 4.7.2_2) 4.7.2

更新:这似乎在装有旧版Boost的Linux机器上运行良好。

更新2:gdb的输出如下所示。

(gdb) run 
Starting program: /Users/yasir/Downloads/mask.util/a.out --help
Reading symbols for shared libraries ++++.. done
Allowed options:
a.out(42256) malloc: *** error for object 0x7fff70ca3500: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

Program received signal SIGABRT, Aborted.
0x00007fff821030b6 in __kill ()
(gdb) bt
#0  0x00007fff821030b6 in __kill ()
#1  0x00007fff821a39f6 in abort ()
#2  0x00007fff820bb195 in free ()
#3  0x00000001001188b4 in std::basic_stringbuf<char, std::char_traits<char>, std::allocator<char> >::overflow ()
(gdb) 

更新3:该程序在Xcode gcc42上运行良好,问题仅出现在MacPorts gcc上。


3
这段代码在我看来是正确的(与我的使用program_options的源代码进行比较)。你能否在gdb中运行它(使用-ggdb3 -O0编译,并运行“gdb --args ./a.out --help”,然后键入“run”和“bt”)? - Rafał Rawicki
@RafałRawicki,我刚刚在用你的标志编译后添加了gdb信息。 - highBandWidth
1个回答

1
您的错误最有可能的原因是程序选项头文件中呈现的接口与编译库中选择的实现之间存在不匹配。这可能是因为您意外地从不同版本的boost中选择了编译库,或者是因为您使用与编译测试程序所用版本不同的编译器编译了库。

有没有办法检查编译库的版本或生成库的编译器是哪个? - highBandWidth
在Linux上,您可以使用objdump -x来查找大部分信息(SO名称,glibc和cxxabi版本)。不过我不知道OS X怎么样。 - Bojan Nikolic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接