ctypes free memory which is allocated in C DLL

Chris Angelico rosuav at gmail.com
Sat Oct 27 16:26:42 EDT 2012


On Sun, Oct 28, 2012 at 2:40 AM, Ken Chen <zlchen.ken at gmail.com> wrote:
> Yes, I agree writing a corresponding API to free the memory is the best practice and best bet.
> Sometimes, the third party API may not provide that.

Then that's a majorly dangerous third party API. The only time it's
safe to provide a half-only API like that is when the code gets
statically linked with the application, so there's a guarantee that
malloc() in one place corresponds to free() in another.

> After digging the Python manual again and again.
> I finally figure out why windll.msvcrt.free is failing.
>
> As the manual stated below, the DLL is using another version of msvcrt lib which is different than the builtin windll.msvcrt. After I explicitly load the msvcrt which built the DLL, things are getting function now.

That's still vulnerable. There's really no guarantee about _anything_
with mismatched memory allocators; it's theoretically possible for
compiler switches to change the behaviour of malloc/free such that
compiling malloc in debug mode and free in release mode would crash
your program. (I don't know off-hand of any compilers/libraries that
do that specifically, but there are similar changes done in other
ways.)

If a DLL allocates memory and doesn't deallocate it, lean on its
author to complete the job.

ChrisA



More information about the Python-list mailing list