Dereference device with a defer call to prevent memory leaks#98
Conversation
…n internal reference so there is no risk of breaking anything.
|
Thanks for your pull request. It looks like this may be your first contribution to a Google open source project (if not, look below for help). Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). 📝 Please visit https://cla.developers.google.com/ to sign. Once you've signed (or fixed any issues), please reply here with What to do if you already signed the CLAIndividual signers
Corporate signers
ℹ️ Googlers: Go here for more info. |
|
@googlebot I signed it! |
zagrodzki
left a comment
There was a problem hiding this comment.
could you also update a comment in https://github.com/google/gousb/blob/master/libusb.go#L212? it is misleading now as it is, since it implies that all devices returned on the list will be "closed" (and so also opened) at some point, but this is not the case.
Done. |
zagrodzki
left a comment
There was a problem hiding this comment.
Should I also create a small unit test for OpenDevices while I am at it?
sure, if you want. You can do that in a separate PR perhaps, this one I think is good to go.
| ret = append(ret, (*libusbDevice)(d)) | ||
| } | ||
| // devices will be dereferenced later, during close. | ||
| // devices must be dereferenced by the caller to prevent memoryleaks |
There was a problem hiding this comment.
s/memoryleaks/memory leaks
|
hey @zagrodzki , |
|
sorry, I assumed you will be able to merge yourself after my approval, but it seems this is not how GitHub flow works... There is one comment left: typo in libusb.go (#98 (comment)) |
This PR fixes the memory leak mentioned in #97
gousb.OpenDevicescurrently only dereferences libusb device pointers when opening is unsuccessful or when the opener returns false.This can cause a memory leak that becomes mostly visible when using multiple libusb contexts in a long running application.
The fix is to always call
c.libusb.dereference(dev)so the device reference counter is decreased when OpenDevices is done. That is not a problem as libusb increases the reference counter internally on thec.libusb.open(dev)call and releases it when we callc.libusb.close(dev)again.