我正在尝试使用 protocol buffers在一个简单的 C++ 程序中。当我用 g++
编译时,程序正常执行和退出。当我用 clang++
编译时,程序失败,提示 pointer being freed was not allocated
。
Protocol Buffer 消息定义
package test;
message Test {
required int32 id = 1;
required string name = 2;
}
主类
#include <iostream>
#include "test.pb.h"
int main(void) {
// Build the original message
test::Test original;
original.set_id(0);
original.set_name("original");
// Serialize the original message
int size = original.ByteSize();
char data[size];
original.SerializeToArray(data, size);
// Deserialize the data into a previously initialized message
test::Test success;
success.set_id(1);
success.set_name("success");
success.ParseFromArray(data, size);
std::cout << success.id() << ": " << success.name() << std::endl;
// Deserialize the data into an uninitialized message
test::Test failure;
failure.ParseFromArray(data, size); // FAILS HERE WITH CLANG++
std::cout << failure.id() << ": " << failure.name() << std::endl;
}
g++ 输出
theisenp$ g++ test.pb.cc main.cpp -lprotobuf -o g++.out
theisenp$ ./g++.out
0: original
0: original
clang++ 输出
theisenp$ clang++ test.pb.cc main.cpp -L/usr/local/lib -lprotobuf -stdlib=libstdc++ -o clang++.out
theisenp$ ./clang++.out
0: original
clang++.out(9948,0x7fff71195310) malloc: *** error for object 0x7fff72ed6330: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
我是 Protocol Buffers 和 Clang 的新手,所以我完全有可能遗漏了一些明显的东西。有什么想法吗?
编辑
关于编译器版本的一些说明。我正在运行 OSX Mavericks (10.9.1)。默认情况下,Mavericks 将对 gcc
和 g++
的调用分别映射到 clang
和 clang++
。我已经独立安装了 gcc
4.8.2 并覆盖了默认行为。
g++版本
theisenp$ g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/local/Cellar/gcc48/4.8.2/libexec/gcc/x86_64-apple-darwin13.0.2/4.8.2/lto-wrapper
Target: x86_64-apple-darwin13.0.2
Configured with: ../configure
--build=x86_64-apple-darwin13.0.2
--prefix=/usr/local/Cellar/gcc48/4.8.2
--enable-languages=c,c++,objc,obj-c++
--program-suffix=-4.8
--with-gmp=/usr/local/opt/gmp4
--with-mpfr=/usr/local/opt/mpfr2
--with-mpc=/usr/local/opt/libmpc08
--with-cloog=/usr/local/opt/cloog018
--with-isl=/usr/local/opt/isl011
--with-system-zlib
--enable-version-specific-runtime-libs
--enable-libstdcxx-time=yes
--enable-stage1-checking
--enable-checking=release
--enable-lto
--disable-werror
--enable-plugin
--disable-nls
--disable-multilib
Thread model: posix
gcc version 4.8.2 (GCC)
clang++版本
theisenp$ clang++ -v
Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.0.2
Thread model: posix
最佳答案
正如评论中所讨论的,重要的是 libprotobuf 使用您在编译代码时使用的相同 stdlib 进行编译,因为 libprotobuf 在其接口(interface)中使用 STL 类型(尤其是 std::string
)。如果您安装了 GCC 4.8,它将使用 GCC 的 libstdc++ 4.8。同时,Xcode 附带的 Clang 将使用 Xcode 附带的任何标准库,因此即使您告诉它 --stdlib=libstdc++
,它也可能是不兼容的版本。
关于c++ - Simple Protocol Buffers 程序在使用 g++ 而不是 clang++ 编译时工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21413852/