[Pyrex] How does pyrex manage memory that is malloced, realloced, etc.

Andreas Kostyrka andreas at kostyrka.org
Sun Jun 26 15:19:00 CEST 2005


Am Freitag, den 24.06.2005, 17:14 -0600 schrieb Nathaniel Haggard:
> An extension that declares a pointer to a struct
> 
> cdef class A:
>        struct1 *s
> 
> Also contains a method that wraps a C function that allocates memory.
> 
> def init_struc1:
>       self.s = c_init()
> 
> Is the memory assigned to self.s safe from overwrites?  How does pyrex
> handle the allocated memory?

Well, such as this

A().init_struct() 

would leak memory.

To demonstrate a correct way:

cdef class MyBuffer:
    cdef char *buffer

    def __init__(self):
        if self.buffer == NULL: # init can be called multiple times
            self.buffer = malloc(128)

    def __dealloc__(self):
        if self.buffer != NULL:
            free(self.buffer)
            self.buffer = NULL # just to be sure!

CPython as such, and our MyBuffer type uses reference counting.
So when you write:

>>> a=MyBuffer()

a points to a MyBuffer instance with refcount == 1.
Our __init__ constructor alloced a 128 byte buffer.

>>> b=a

now a and b point to the same instance with refcount == 2

>>> del a

now b points to our instance with refcount == 1

>>> del b

now the refcount of our MyBuffer instance has gone to 0 and it's being freed,
so our __dealloc__ destructor (which is a Pyrex specific name) got's called and
frees the 128 byte buffer.

Andreas
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Dies ist ein digital signierter Nachrichtenteil
Url : http://lists.copyleft.no/pipermail/pyrex/attachments/20050626/4b9cce28/attachment.bin


More information about the Pyrex mailing list