Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning pointers from the class. Who is responsible for delete?

Tags:

c++

c

abi

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?

like image 456
Slava Avatar asked Feb 21 '23 07:02

Slava


2 Answers

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.

like image 194
MSalters Avatar answered Apr 06 '23 10:04

MSalters


Make the caller responsible for allocating and freeing memory.

like image 32
pmg Avatar answered Apr 06 '23 10:04

pmg