[fpc-pascal] How to free memory allocated by C++ library

Henry Vermaak henry.vermaak at gmail.com
Thu Jun 2 14:27:08 CEST 2011


On 02/06/11 13:04, Jonas Maebe wrote:
>
> On 02 Jun 2011, at 10:35, Henry Vermaak wrote:
>>
>> If you add cmem to the start of your uses list, all the memory operations are routed through the c memory manager.  You should then be able to use Free safely for pointers that were allocated by your library.
>
> That is incorrect. The cmem unit adds extra size information to all allocated memory blocks (for so that memsize() works). Additionally, most C++ memory allocations happen via new/delete, and using libc's "free" to free a memory block allocated by "new" is almost guaranteed to cause crashes down the line.

So it works in C, but not C++?  Or have I completely misunderstood the 
documentation?

> You'd have to write a separate cppmem unit that exports the various kinds of new/delete helpers. To make things extra fun, their mangled names depend on the used C++ compiler and sometimes even version (and also which helpers exist can change, e.g., I believe older g++ versions had a single helper for delete and delete[], which the current versions have two different ones for that).

Or write a function for the library that takes care of disposing pointers.

Henry



More information about the fpc-pascal mailing list