Files
opencv-MIRROR/modules/flann/test
uwezkhan 2f5613fd94 Merge pull request #30559 from uwezkhan:flann-kmeans-load-roots
flann: reallocate the kmeans tree roots in loadIndex 🤖🤖🤖 - #30559

`KMeansIndex::loadIndex` reads `trees_` from the saved file and then calls `load_tree(stream, root_[i], i)` for every tree, but it never reallocates `root_`. That array was sized by the constructor from the `trees` index parameter. `cv::flann::Index::load` builds the index with only `algorithm` set, so `root_` always has the default single slot. A saved KMeans index whose `trees_` field is 2 or more makes `load_tree` write node pointers past the end of `root_`, and `free_centers()` and the destructor later read the same slots. With ASan this is a heap-buffer-overflow WRITE of size 8 in `load_tree`, 0 bytes after the 8-byte region allocated in the `KMeansIndex` constructor. The same path is reached through the composite and autotuned loaders, which call `KMeansIndex::loadIndex`.

The fix frees `root_` and reallocates it with the loaded tree count, as `HierarchicalClusteringIndex::loadIndex` and `KDTreeIndex::loadIndex` already do. Both arrays are value-initialized and reset to NULL before the reads, so a truncated file that throws partway through only leaves NULL slots for the destructor. Files saved by OpenCV always store the `trees` value they were built with, so they load exactly as before. Added `Flann_KMeansIndex.load_more_trees_than_default` to `opencv_test_flann`, which stores the same tree twice under `trees_ = 2`. It fails under ASan without the fix. With the fix it passes, along with the rest of `opencv_test_flann`.

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [ ] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
2026-10-29 15:48:36 +03:00
..
2018-02-03 19:39:47 +00:00