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上解決這個問題?