简体   繁体   English

dlmalloc + CPP + strdup + Mac OS X =崩溃

[英]dlmalloc + CPP + strdup + Mac OS X = crash

I am using the dlmalloc library on Mac OS X in a mixed C/C++ environment. 我在混合C / C ++环境中的Mac OS X上使用dlmalloc库。

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. 只能在Mac OS X上使用。如果我在Ubuntu或Windows(Cygwin)中尝试相同的代码,则不会发生。

What's going on here? 这里发生了什么? If I use malloc directly rather than strdup it won't crash. 如果我直接使用malloc而不是strdup,它将不会崩溃。 My guess is that the default malloc and dlmalloc are being mixed. 我的猜测是默认的malloc和dlmalloc混合在一起了。 Possibly because strdup is using the default malloc while the free call is using dlmalloc's free. 可能是因为strdup使用默认的malloc,而free调用使用的是dlmalloc的free。 If so, why doesn't this happen on other platforms? 如果是这样,为什么在其他平台上不发生这种情况? How do I work around this on Mac OS X? 如何在Mac OS X上解决此问题?

I think I've figured out what's happening. 我想我已经知道发生了什么事。 It has to do with the way Mac OS X forces you to use dynamic libc. 它与Mac OS X强制您使用动态libc的方式有关。 dlmalloc is compiled statically into the exe. dlmalloc被静态编译到exe中。 But regular malloc is being used in the dynamic libc. 但是动态libc中使用了常规的malloc。 When you call strdup, it uses regular malloc, but then when free is called it is using dlmalloc. 当您调用strdup时,它将使用常规的malloc,但是在调用free时,它将使用dlmalloc。 Boom. 繁荣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM