简体   繁体   English

C++ 释放共享库中动态分配的 memory 导致崩溃

[英]C++ freeing dynamically allocated memory in shared library causing crash

I have a shared library mod.so and it has a function getptr to return pointer to a dynamically allocated memory.It also has a function Unload which frees the memory which was allocated. I have a shared library mod.so and it has a function getptr to return pointer to a dynamically allocated memory.It also has a function Unload which frees the memory which was allocated. The main program loads this shared library at runtime and gets the pointer from getptr function but when Unload function is called it gives me Segmentation Fault.主程序在运行时加载这个共享库并从 getptr function 获取指针,但是当 Unload function 被调用时,它给了我分段错误。

main.cpp主文件

    #include <iostream>
#include <dlfcn.h>
using namespace std;
int main()
{
  void* module = dlopen("mod.so",RTLD_LAZY);
  typedef int*(*func)();
  typedef void(*func1)();
  func f = (func)dlsym(module,"getptr");
  func1 b = (func1)dlsym(module,"Unload");
  int* p = f();
  b();
}

mod.cpp模组.cpp

    #include <iostream>
#include <vector>
using namespace std;
vector<int*> allocated;
extern "C"
{
  int* getptr()
  {
    int* p = new int;
    *p = 1024;
    allocated.push_back(p);
    return p;
  }
  void Unload()
  {
    for(auto e: allocated)
      delete e;
  }
}

The mod.cpp is compiled as: mod.cpp 编译为:

g++ -shared mod.cpp -o mod.so -fPIC g++ -shared mod.cpp -o mod.so -fPIC

dlopen("mod.so",RTLD_LAZY) returns NULL. dlopen("mod.so",RTLD_LAZY)返回 NULL。 Try this:尝试这个:

void* module = dlopen("./mod.so",RTLD_LAZY);
if (!module) {
    fprintf(stderr, "error in dlopen: %s\n", dlerror());
    return 1;
}

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

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