0
我在混合的C/C++环境中使用Mac OS X上的dlmalloc库。dlmalloc + CPP + strdup + Mac OS X =崩溃
下面的简单代码
/// strdup-test.cpp
///
#include <iostream>
#include <string>
int main(int argc, char **argv) {
std::string s1("foo");
char *c1=strdup(s1.c_str());
std::cerr << c1 << std::endl;
// segfault?
free(c1);
return 0;
}
当编译这样
gcc -c malloc.c
g++ strdup-test.cpp -o strdup-test malloc.o
会崩溃这样
$ ./strdup-test
foo
Segmentation fault
但只有在Mac OS X 如果我试试这个在Ubuntu或Windows(Cygwin)中相同的代码不会发生。
这是怎么回事?如果我直接使用malloc而不是strdup,它不会崩溃。我的猜测是默认的malloc和dlmalloc混合在一起。可能是因为strdup使用默认的malloc,而免费通话使用的是dlmalloc的免费。如果是这样,为什么不在其他平台上发生?我如何在Mac OS X上解决这个问题?