Do I need to free memory returned from a C function called via CFFI?

隐身守侯 提交于 2019-12-06 01:53:26

From the documentation on Working with pointers, structures and arrays, and quoting the correct section:

Any operation that would in C return a pointer or array or struct type gives you a fresh cdata object. Unlike the “original” one, these fresh cdata objects don’t have ownership

Therefore you must free it, there is no way it can assume the ownership: In C there are many functions that return a pointer to a constant string in memory, that not only it is not dynamically allocated, it is not allocated, or modifiable at all, for example. Freeing those would be very erroneous.


Also for free, the documentation says the following:

An alternative is to declare and call the C malloc() and free() functions, or some variant like mmap() and munmap(). Then you control exactly when the memory is allocated and freed. For example, add these two lines to your existing ffibuilder.cdef():

void *malloc(size_t size);
void free(void *ptr);

Since it is very important that the correct C standard library free is used for a pointer returned by strdup you cannot rely CFFI to magically do the correct thing, but instead as you suspected, you should expose free(). You can also use the gc as suggested by Barmar to register an automatic clean up, if needed:

x = ffi.gc(x, lib.free)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!