[fpc-pascal] How to free memory allocated by C++ library
Jonas Maebe
jonas.maebe at elis.ugent.be
Thu Jun 2 14:04:29 CEST 2011
On 02 Jun 2011, at 10:35, Henry Vermaak wrote:
> On 01/06/11 21:27, Malcolm Poole wrote:
>> Working from the instructions in CinFreepascal.pdf (
>> ftp://ftp.freepascal.org/pub/fpc/docs-pdf/CinFreePascal.pdf ) I have
>> written an interface library to the C++ library libtesseract (
>> http://code.google.com/p/tesseract-ocr ).
>>
>> Everything appears to work well but I am unsure about how to free memory
>> which has been reserved by a libtesseract function and returned as a
>> result. The original documentation states that "The calling function
>> must delete [] after use", but the application crashes with an Access
>> Violation if I try to free the memory with Dispose or Freemem. I can
>> confirm that the array of Integer pointed to by the result of
>> tesseract_AllWordConfidences contains valid data.
>
> 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.
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).
Jonas
More information about the fpc-pascal
mailing list