www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - `free` for struct with C bindings.

reply Jonathan <JonathanILevi gmail.com> writes:
I am using a C bindings library 
(https://code.dlang.org/packages/xcb-d).

I am following through a tutorial that was written for the C 
library directly and just making the minor changes to make it 
work with D.

I ran into a problem. The library ends up giving me a struct 
pointer.

```
xcb_generic_event_t*	event;
event = xcb_wait_for_event (connection);
free (event);
```

The problem is the `free` function.  It is not provided by the 
library but is part of the C standard library (in stdlib.h).

Do I need to call this function with my D code?  I tried using 
the `core.memory.GC.free` function from the D standard library 
and it compiled and ran but that does not necessarily mean there 
are not memory leaks (it also ran with the line entirely removed).

Do I need to call the `free` function with my D code because I 
need to free memory that was allocated in C code?
May 14 2018
next sibling parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 05/14/2018 03:03 PM, Jonathan wrote:

 Do I need to call the `free` function with my D code because I need to 
 free memory that was allocated in C code?
Yes, you have to free the memory with C's free(): void main() { import core.stdc.stdlib; auto p = malloc(42); free(p); } Ali
May 14 2018
prev sibling parent ag0aep6g <anonymous example.com> writes:
On 05/15/2018 12:03 AM, Jonathan wrote:
 ```
 xcb_generic_event_t*    event;
 event = xcb_wait_for_event (connection);
 free (event);
 ```
 
 The problem is the `free` function.  It is not provided by the library 
 but is part of the C standard library (in stdlib.h).
D has the C functions in core.stdc. So: import core.stdc.stdlib: free; [...]
 I tried using the 
 `core.memory.GC.free` function from the D standard library and it 
 compiled and ran but that does not necessarily mean there are not memory 
 leaks (it also ran with the line entirely removed).
core.memory.GC.free is a different function. It works on GC-managed pointers. Don't call it on pointers that come from C libraries.
May 14 2018