Skip to content

Memory leak in dart:ffi samples #93

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

Closed
xzfc opened this issue Mar 17, 2021 · 2 comments · Fixed by #101
Closed

Memory leak in dart:ffi samples #93

xzfc opened this issue Mar 17, 2021 · 2 comments · Fixed by #101

Comments

@xzfc
Copy link

xzfc commented Mar 17, 2021

Here the memory is allocated in reverse():

char *reversed_str = (char *)malloc((length + 1) * sizeof(char));

Here it used in toDartString():

final reversedMessage =
reverse(backwards.toNativeUtf8(), backwards.length).toDartString();

It is not clear how the allocated memory should be freed.

Should it be done using malloc.free() call or there is a more conventional way to do it in dart? OTOH, if toDartString() actually takes ownership for this C string and there is no memory leak, then this behavior should be documented somewhere.

@dcharkes
Copy link
Contributor

The snippet actually contains two memory leaks, backwards.toNativeUtf8() also leaks.

final reverse = dylib.lookupFunction<reverse_native, Reverse>('reverse');
final backwards = 'backwards';
final reversedMessage =
reverse(backwards.toNativeUtf8(), backwards.length).toDartString();
print('$backwards reversed is $reversedMessage');

should be

  final reverse = dylib.lookupFunction<reverse_native, Reverse>('reverse');
  final backwards = 'backwards'.toNativeUtf8();
  final reversedMessage =
      reverse(backwards, backwards.length).toDartString();
  malloc.free(backwards);
  print('$backwards reversed is $reversedMessage');
  malloc.free(reversedMessage);

However, this is slightly ugly, because now Dart is calling free on a malloc in C.

It would be cleaner to add a void free_string(char* str) to C which does the freeing and invoke that from Dart instead of malloc.free(reversedMessage). That way you are sure that malloc and free match up from the same compilation unit (which can be a problem on Windows - you cannot use free from one dll on a malloced pointer from another dll).

@xzfc
Copy link
Author

xzfc commented Mar 18, 2021

Thanks. I think it would make sense to cover this in the sample code since memory management is a common issue with ffi code.

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 a pull request may close this issue.

2 participants