rainyl / opencv_dart

OpenCV bindings for Dart language and Flutter.
https://pub.dev/packages/opencv_dart
Apache License 2.0
78 stars 10 forks source link

Memory leak #102

Closed cike111 closed 1 week ago

cike111 commented 1 week ago

Describe the bug In iOS, if you call grayMat.set(y, x, grayLevel) every 2 seconds, it will cause the memory to continuously increase

To Reproduce 17186112505115

pubspec.yaml code:

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.6
  opencv_dart: ^1.0.9

mian.dart

 void initState() {
    super.initState();
    _timer = Timer.periodic(Duration(milliseconds: 2000), (timer) {
      test();
    });
  }
test(){
  CV.Mat grayMat = CV.Mat.zeros(
     1000, 1000, CV.MatType.CV_8UC1);
  int maxY = grayMat.rows - 1;
  int maxX = grayMat.cols;
  for (int y = maxY; y >= 0; y--) {
    for (int x = 0; x < maxX; x++) {
      grayMat.set<int>(0, 0, 30);
    }
  }
}
rainyl commented 1 week ago

Confirmed, Mat_Set will cause a memory leak even though manually dispose Mat, but every thing looks ok, not sure why...

https://github.com/rainyl/opencv_dart/blob/b71f6d1dd01f62b91cfa4b4e2340fc4bdd7510c4/src/core/core.cpp#L708-L713

https://github.com/rainyl/opencv_dart/blob/b71f6d1dd01f62b91cfa4b4e2340fc4bdd7510c4/lib/src/core/mat.dart#L517-L519

rainyl commented 1 week ago

@cike111 v1.0.10 and 2.0.0-dev.12 have been published, please update and try if it has been solved, if not please open this issue again.

cike111 commented 1 week ago

@rainyl Your approach seems to have some effect, but it hasn't completely solved the problem.

image

rainyl commented 1 week ago

@cike111 emmmmm..., alright, I suggest you to dispose it manually if you have to create mats in a loop, due to the limitation of dart GC (https://github.com/rainyl/opencv_dart/issues/64#issuecomment-2137342504), the attached native resources may not be freed timely, in the above example, change it to

test(){
  CV.Mat grayMat = CV.Mat.zeros(
     1000, 1000, CV.MatType.CV_8UC1);
  int maxY = grayMat.rows - 1;
  int maxX = grayMat.cols;
  for (int y = maxY; y >= 0; y--) {
    for (int x = 0; x < maxX; x++) {
      grayMat.set<int>(0, 0, 30);
    }
  }
  // add this line
  grayMat.dispose();
}

If the problem still exists, then I have no more ideas too, and I have no apple devices so can't debug it, on my windows PC every thing is ok.