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

Malcolm Poole malcolm at lingua-z.co.uk
Thu Jun 2 19:15:57 CEST 2011


On 02/06/11 13:27, Henry Vermaak wrote:
> 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.
>
Yes, that was the answer I reached an hour after posting. It's 
surprising how writing to a mailing list can concentrate the mind :)

BTW, the library works very well. It interfaces with libtesseract v.3. 
It and bindings for many related leptonica image processing functions 
are at
http://code.google.com/p/ocrivist/source/browse/

Malcolm



More information about the fpc-pascal mailing list