chicken-users
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Chicken-users] malloc'd memory


From: Thomas Chust
Subject: Re: [Chicken-users] malloc'd memory
Date: Mon, 26 Jan 2015 00:19:23 +0100
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Thunderbird/31.4.0

On 2015-01-25 23:21, Alexej Magura wrote:
> If I have a function that returns a malloc'd pointer, or that needs to
> have a buffer malloc'd, is it more idiomatic to (1) malloc and free in
> the caller function (which is C's idiom, IIRC), or (2) malloc it in C
> and then just return the pointer for free'ing by Chicken once the caller
> function is done with the pointer?
> [...]

Hello,

the best integration with CHICKEN's memory management would be achieved
by allocating through CHICKEN's library, for example as blobs, passing
the pointer to some foreign initialization function and relying on
garbage collection to free the memory. However, the C library should
then not rely on fixed memory positions of those objects.

A common idiom for C libraries is to provide both allocation and
deallocation functions. To integrate this with CHICKEN's automatic
memory management, it would be necessary to attach finalizers calling
the deallocators to pointers returned from the allocators. However, this
can cause resource problems if the allocated objects are very large,
while the CHICKEN garbage collector only sees the small pointers.

Additional caveats apply if the allocated objects need to be globally
reachable both from CHICKEN code and foreign code.

Providing allocators but no deallocators from a C library and requiring
the caller to use the standard free function to dispose resources is a
bad idea, because this can cause linkage problems in some situations.
For example, depending on the chosen runtime library and linkage model,
dynamic libraries under Windows may have a separate heap and a separate
copy of the malloc and free functions distinct from that of the calling
executable; in that case, passing a pointer malloced in the library to
free in the calling executable will cause invalid memory accesses.

Ciao,
Thomas


-- 
When C++ is your hammer, every problem looks like your thumb.




reply via email to

[Prev in Thread] Current Thread [Next in Thread]