Skip to content
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

Memory Leak issue in iOS #32

Open
tengdaoxiong opened this issue Dec 31, 2023 · 0 comments
Open

Memory Leak issue in iOS #32

tengdaoxiong opened this issue Dec 31, 2023 · 0 comments

Comments

@tengdaoxiong
Copy link

tengdaoxiong commented Dec 31, 2023

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 ...

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

No branches or pull requests

1 participant