I am using the dlmalloc library on Mac OS X in a mixed C/C++ environment.
The following simple code
/// 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;
}
when compiled like this
gcc -c malloc.c
g++ strdup-test.cpp -o strdup-test malloc.o
will crash like this
$ ./strdup-test
foo
Segmentation fault
but only on Mac OS X. If I try this same code in Ubuntu or Windows (Cygwin) it won't happen.
What's going on here? If I use malloc directly rather than strdup it won't crash. My guess is that the default malloc and dlmalloc are being mixed. Possibly because strdup is using the default malloc while the free call is using dlmalloc's free. If so, why doesn't this happen on other platforms? How do I work around this on Mac OS X?