简体   繁体   English

Linux C / C ++在动态库中分配/释放内存

[英]Linux C/C++ allocate/deallocate memory in dynamic library

I have to split my application into several logical modules. 我必须将我的应用程序拆分为几个逻辑模块。

mainapp : mainapp

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

Where each module is an *.so library, which will be loaded during runtime. 每个模块都是*.so库,它将在运行时加载。

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? 可以,在mainapp端释放/删除这个内存吗?

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

What about a malloc/free implementations. 如何实现malloc / free实现。 Is it possible, that library will use another one then mainapp? 是否可能,该库将使用另一个然后mainapp?

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. 这允许不同的模块毫无困难地使用不同的分配器(malloc / free,new / delete,slab allocator等)。

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. 在Posix系统上,进程中只能有一个malloc (和free )实现,所以如果getIntData的定义是“返回一个必须free释放的指针”,那么你getIntData了。 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 . 另一方面,我认为可以编写两个可用于编写module1和module2的C ++编译器,但这些编译器无法 delete另一个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. 如果有一个偶然的机会,您可能需要将这个批次移植到Windows,那么您真的希望模块释放它们分配的内存。 Different DLLs can have different heaps and all manner of fun problems can ensue. 不同的DLL可以具有不同的堆,并且可以产生各种有趣的问题。 (As @trojanfoe says in comments: Just the difference between debug and release builds can be enough to cause grief.) (正如@trojanfoe在评论中所说:调试和发布版本之间的差异足以引起悲伤。)

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. 我只建议使用std::unique_ptr如果你可以保证所有模块总是使用相同的编译器标志使用相同版本的相同编译器构建。 (I am a strong believer in keeping dynamic library interfaces as simple and C-like as possible.) (我坚信保持动态库接口尽可能简单和像C一样。)

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

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