本文介绍了Linux下C / C ++在分配动态库/释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的应用程序分割成多个逻辑模块。

I have to split my application into several logical modules.

mainapp :

mainapp:


  • module1.so

  • module2.so

  • module3.so


其中每个模块是 *。所以库,这将在运行时被加载。

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();

是否确定,以释放/删除 mainapp 一边这个内存?

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

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

有关的malloc /免费实现什么。是否有可能,该库将使用另外一个则mainapp?

What about a malloc/free implementations. Is it possible, that library will use another one then 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);

这使得不同的模块毫无困难地使用不同的分配器(的malloc /免费,新/删除,slab分配器等)。

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

在POSIX系统只能有的malloc一个实现(和免费)的一个过程,因此,如果 getIntData定义是返回必须由免费被free'd指针,那么你会没事的。在另一方面,我认为这将是可以写,可以用来写模块1和模块2两个C ++编译器,但它的无法删除通过其他的新分配的内存。 (虽然我不的认为的目前存在这样的编译器)。

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).

如果有你可能曾经有这个端口很多到Windows机会的边远一线希望,那么你的真正的希望模块释放他们分配的内存。不同的DLL可以有不同的至爱,有趣的问题都可以地随之而来。 (正如@trojanfoe说,在注释:只是调试和发布之间的差异构建可以足以使人忧愁)

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.)

我只推荐使用的std ::的unique_ptr 如果你能保证所有的模块都总是会使用相同的编译器相同的编译器的相同版本的构建标志。 (我是在保持动态库接口,-像C尽可能简单和强大的信徒。)

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.)

这篇关于Linux下C / C ++在分配动态库/释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 01:33