Linux C/C++ allocate/deallocate memory in dynamic library

主宰稳场 提交于 2019-12-23 20:31:30

问题


I have to split my application into several logical modules.

mainapp:

  • module1.so
  • module2.so
  • module3.so
  • and so on

Where each module is an *.so library, which will be loaded during runtime.

Each module shares the same interface and will return some array of data. For example:

int *ptr = module1->getIntData();

Is it OK, to free/delete this memory on mainapp side?

int *ptr = module1->getIntData();
delete ptr; //(or free(ptr))

What about a malloc/free implementations. Is it possible, that library will use another one then mainapp?


回答1:


I would strongly recommend that the module which does the allocation is also responsible for doing the de-allocation. Thus:

int *ptr = module1->getIntData();
...
module1->freeIntData(ptr);

This allows different modules to use different allocators (malloc/free, new/delete, slab allocator, etc) without difficulty.

On Posix systems there can only be one implementation of malloc (and free) in a process, so if the definition of getIntData is "returns a pointer which must be free'd by free" then you would be alright. On the other hand, I think it would be possible to write two C++ compilers which could be used to write module1 and module2, but which couldn't delete memory allocated by the other's new. (Although I don't think such compilers currently exist).

If there is the remotest glimmer of a chance you might ever have to port this lot to Windows, then you really want the modules to deallocate the memory they allocated. Different DLLs can have different heaps and all manner of fun problems can ensue. (As @trojanfoe says in comments: Just the difference between debug and release builds can be enough to cause grief.)

I would only recommend using std::unique_ptr if you can guarantee that all the modules are always going to be built with the same version of the same compiler using identical compiler flags. (I am a strong believer in keeping dynamic library interfaces as simple and C-like as possible.)



来源:https://stackoverflow.com/questions/36420174/linux-c-c-allocate-deallocate-memory-in-dynamic-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!