Skip to content

[ffi] Fix memory leaks #101

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 3, 2021
Merged

[ffi] Fix memory leaks #101

merged 1 commit into from
May 3, 2021

Conversation

dcharkes
Copy link
Contributor

Closes #93.

Native memory allocated in Dart is freed in Dart (.toNativeUtf8() -> calloc.free()).

Native memory allocated in C is freed in C (malloc -> free).

This symmetry makes it such that we never end up calling free on something malloced from another definition of malloc than the one that is in the same native library as free.

@dcharkes dcharkes requested review from johnpryan and mit-mit April 19, 2021 07:55
@nmfisher
Copy link

I've written some code that mallocs a char pointer on the C side, passes back to Dart via FFI then calls toDartString() and calloc.free.

Judging from this commit, though, my code should actually be crashing but it's worked fine so far (admittedly it's basic demo code).

Any clarification? Is toDartString() calling free on the C-side under the hood somewhere?

@dcharkes
Copy link
Contributor Author

I've written some code that mallocs a char pointer on the C side, passes back to Dart via FFI then calls toDartString() and calloc.free.

This will most likely work fine as long as you're not on Windows. And on Windows it can work, but not always.

See https://stackoverflow.com/a/8722008/8136619

@nmfisher
Copy link

Thanks!

@johnpryan johnpryan merged commit b8ffd62 into master May 3, 2021
@mit-mit mit-mit deleted the ffi/fix-memory-leaks branch December 9, 2021 12:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Memory leak in dart:ffi samples
3 participants