Question

I have a C++ class which implements binary compatible interface (to be used as a shared library), thus returning only C types. strings as const char*, void pointers, and pointers to other classes with binary compatible interface. The question is how shall I organize memory management, shall I return constant pointers to existing class data (danger of using outdated pointer by user), and release memory there myself, or rather pointers to some heap variables and make user responsible for deleting those pointers later, or??? Is there some general guidelines for that?

Was it helpful?

Solution

In a "binary compatible interface", using a C interface, you do not assume a shared heap. Therefore, the party which allocates memory from a heap is the party that returns it to that heap.

You can get spectacular failures and/or silent corruption if you allocate a block from one heap, pass it across a C interface, and then have the other side delete it.

OTHER TIPS

Make the caller responsible for allocating and freeing memory.

Both are accepted and used in production environments, as long as they are clearly and thoroughly documented.

This is really up to you.

A good object-oriented approach is to have the class itself manage the memory. Much of the benefit of OOP is to encapsulate functionality as best you can. So you might design it so the code can call your class methods without worrying about how memory is being allocated or freed because it's managed by the class.

However, there are times when this approach doesn't work because there's no good way for the class to know when the memory is no longer required. For those cases, you can either just have the caller allocate the memory (and later free it), or simply stipulate that the caller must free the memory that is allocated and returned from the class.

It's done both ways. There are not really any hard and fast rules here.

If it is possible, use smartpointers like unique_ptr or shared_ptr. (Which should be no problem since you're already wrapping the C functions, if I got you right.)

I would say that the caller has the responsibility to free the data. Also note that you can not use new in case the caller is not a C++ application.

If you're writing to an existing API, then you do whatever that API requires. You don't have any choice in the matter; the API has specified who is responsible for what, and the code on the other side of the API is going to expect your implementation to conform.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top