C++ 导致segfault的共享库

C++ 导致segfault的共享库,c++,segmentation-fault,shared-libraries,C++,Segmentation Fault,Shared Libraries,我创建了一个小型共享库,它重载malloc和co。它编译成功,但当我试图用它执行其他程序时,它会导致segfault 到目前为止,我在尝试解决问题时采取了以下步骤: 1. Make sure the .so is executable. 2. Tried debugging using Valgrind and gdb.(see GDB output below) 3. Looked at other related questions on SO and tried to adopt the

我创建了一个小型共享库,它重载malloc和co。它编译成功,但当我试图用它执行其他程序时,它会导致segfault

到目前为止,我在尝试解决问题时采取了以下步骤:

1. Make sure the .so is executable.
2. Tried debugging using Valgrind and gdb.(see GDB output below)
3. Looked at other related questions on SO and tried to adopt the suggestions given. 
使用执行Test.cpp

 LD_PRELOAD=/home/absolute/path/mylib.so ./a.out 
导致了一个故障

Test.cpp

#include <stdlib.h>
#include <iostream>

int main () {

  size_t size = sizeof(int);
  void* ptr = malloc(size);
  std::cout<<"Called malloc() " << ptr << std::endl;
  free(ptr);
return 0;
Gdb输出:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000000002 in ?? ()
Valgrind输出:

 ==19131== Jump to the invalid address stated on the next line
 ==19131==    at 0x2: ???
 ==19131==    by 0xFFF000082: ???
 ==19131==    by 0xFFF000092: ???
 ==19131==  Address 0x2 is not stack'd, malloc'd or (recently) free'd
 ==19131== 
 ==19131== 
  ==19131== Process terminating with default action of signal 11 (SIGSEGV)
 ==19131==  Bad permissions for mapped region at address 0x2
 ==19131==    at 0x2: ???
 ==19131==    by 0xFFF000082: ???
 ==19131==    by 0xFFF000092: ???
由于mylib没有代码,所以我无法判断哪条指令试图寻址0x2,也无法想出任何有助于我更接近解决方案的方法。 任何为我指明写作方向的帮助都会非常有用

TIA.

此代码:

void* malloc(size_t size) noexcept {
    auto fptr = (void* (*)(size_t))dlsym(handle, "malloc");
    void* ptr  = fptr(size);
    std::cout<<"malloc"<<std::endl;
char* foo = "malloc\n";
保证在任何
dlsym
实现上永远重复出现并耗尽堆栈,该实现本身
malloc
s内存

此代码:

void* malloc(size_t size) noexcept {
    auto fptr = (void* (*)(size_t))dlsym(handle, "malloc");
    void* ptr  = fptr(size);
    std::cout<<"malloc"<<std::endl;
char* foo = "malloc\n";

不应该编译任何合理的C++编译器。这是gdb回溯;(gdb)回溯#0 0x0000000000000002英寸??()#1 0x00007FFFFFE18D英寸??()#2 0x00007FFFFFE1C2英寸??我还没有完全理解这个问题:我已经删除了所有std::cout行,但仍然以segfault结束。回溯对我来说不是很有用,因为我不知道错误发生在哪里。你能给我指一下正确的方向吗?另外,我在Ubuntu 16.04上使用的是g++7.2.0版。当我查看我与nm共享的库的对象符号时,我注意到所有的libc函数,如mmap、fsnyc,都是未定义的。这是问题的一部分吗?如何确保libc已初始化?@InfoGirl当我删除对

std::cout
的调用时,我无法再重现您的崩溃。如果您将测试程序直接链接到mylib.so(而不是
LD_PRELOAD
加载它),您可能能够获得更好的堆栈跟踪。我意识到问题在于FIrstfit_heap,当我注释它+std::cout它工作时。这个类的构造函数是:Firstfit_heap(Memory&mem):heap(mem){…},但是我需要这个类来使用我自己的alloc函数。什么会导致类出现这种行为?@InfoGirl您可能应该问一个单独的问题,并显示相关代码。