flutter_pytorch_mobile icon indicating copy to clipboard operation
flutter_pytorch_mobile copied to clipboard

Memory Leak issue in iOS

Open tengdaoxiong opened this issue 1 year ago • 0 comments
trafficstars

The memory leak happens very slowly, but could be worth fixing for some use cases. Just 2 minor changes

Location 1: iOS/Classes/Helpers/UIImageExtension.m

Issue: The normalize: method in the UIImageExtension class has a potential memory leak caused by not freeing allocated memory.

Leak Source: The rawBytes pointer is allocated memory using calloc but is never released.

Solution:

Free rawBytes: After processing the image data, free the memory allocated to rawBytes using free(rawBytes) before returning "normalizedBuffer"

  • (nullable float*)normalize:(UIImage*)image withMean:(NSArray<NSNumber*>)mean withSTD:(NSArray<NSNumber>*)std { ... .... free(rawBytes); // Add this line to fix memory leak return normalizedBuffer; }

Location 2: iOS/Classes/PyTorchMobilePlugin.mm

Issue: The memory leak occurs in the image prediction functionality (case 2 block) of the handleMethodCall:result: method in the PyTorchMobilePlugin class. The leak is caused by dynamically allocated memory that is not freed properly.

Leak Source: The leak is traced back to the UIImageExtension's normalize: method, which allocates memory for the input float array. This memory allocation is necessary for image processing but becomes a liability if not handled correctly.

Solution: Here's the corrected section of the code:

case 2: ... ... try { NSArray<NSNumber*>* output = [imageModule predictImage:input withWidth:width andHeight: height]; result(output); } catch (const std::exception& e) { NSLog(@"PyTorchMobile: %s", e.what()); } free(input); // // Add this line to fix memory leak break; ... Rest of the code ...

tengdaoxiong avatar Dec 31 '23 09:12 tengdaoxiong