Thread overview
`free` for struct with C bindings.
May 14, 2018
Jonathan
May 14, 2018
Ali Çehreli
May 14, 2018
ag0aep6g
May 14, 2018
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
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 15, 2018
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.