gpt4 book ai didi

c++ Floodfill算法在Xcode中崩溃

转载 作者:行者123 更新时间:2023-11-28 04:29:24 28 4
gpt4 key购买 nike

我有一个简单的 floodfill 函数,除了它在运行时因过多的释放而崩溃。

#include <vector>
cv::Mat fillLayer(cv::Mat filledEdge, int y, int x, int oldColor, float newColor){
cv::Size shape = filledEdge.size();
int h = shape.height;
int w = shape.width;

std::vector<int> theStackx = {x};
std::vector<int> theStacky = {y};


while (theStacky.size() > 0){
y = theStacky.back();
x = theStackx.back();
theStacky.pop_back();
theStackx.pop_back();

if (x == w){
continue;
}
if (x == -1){
continue;
}
if (y == -1){
continue;
}
if (y == h){
continue;
}

if (filledEdge.at<float>(y, x) != oldColor){
continue;
}

filledEdge.at<float>(y, x) = newColor;

//up
theStacky.push_back(y + 1);
theStackx.push_back(x);
//down
theStacky.push_back(y - 1);
theStackx.push_back(x);
//right
theStacky.push_back(y);
theStackx.push_back(x + 1);
//left
theStacky.push_back(y);
theStackx.push_back(x - 1);
}
return filledEdge;

}

贯穿floodfill的函数是fillSurface。它遍历 Mat 中的所有像素,并在每个 floodfill 中用不同的颜色填充它们

fillSurface(cv::Mat filledEdge, int oldColor) {
std::vector<float> layers; //list all the different colors in mat
cv::Size shape = filledEdge.size();
int h = shape.height;
int w = shape.width;
float newColor;
// run through all the pixels in Mat
for(int y = 0; y!= h; y++){
for(int x = 0; x!= w; x++){
// only run floodfill if current pixel is oldColor
if (filledEdge.at<float>(y, x) == oldColor){
//newColor is random float to fill in to floodfill
newColor = static_cast <float> ((rand()) / (static_cast <float> (RAND_MAX/253)) + 1);
// add newColor to list of layers
layers.push_back(newColor);
//run flood fill replacing old color with new color
filledEdge = fillLayer(filledEdge, y, x, oldColor, newColor);

}
}
}
}

这是我收到的错误:

Incorrect checksum for freed object 0x7fea0d89dc00: probably modified after being freed.

我所做的调试是在 malloc_error_break() 上设置一个断点,以查看我在哪里得到中断。它确实导致了 floodfill 功能。

enter image description here

我想知道是否有办法解决这个问题。如果不是,最好的选择是什么?

最佳答案

如果没有 MCVE,我无法直接重现您的问题,而且我自己也不了解 CV。但我可以做出一些可能有帮助的猜测。

运行时错误指出“释放对象的校验和不正确......:可能在释放后被修改。”

给您的第一个提示是,像这样的堆检查通常只在堆操作发生时发生——而不是在损坏发生时发生。您的代码中没有任何显式堆操作(例如,newdelete)。此处的堆使用来自标准库 (vector) 和 cv (Mat) 中有据可查且经过充分测试的数据结构。

第二个提示是可能在被释放后被修改,但这是不完整的——另一种可能性是一些代码写在它的边界之外——缓冲区溢出或不正确的数组索引或类似的东西。

最后一点将我们带到了 Mat 类的 CV 文档中,其中没有提到如果您对 Mat 进行索引不当会发生什么情况。它确实有关于确保您使用正确的元素类型进行访问的警告,否则事情可能会出错。这些东西在一起可能是一个非常强烈的暗示,如果你错误地访问垫子,可能会发生坏事。就像,如果你正在写作,可能是内存损坏。

这些东西,连同我上面关于你声明变量 hw 但不使用它们的评论 - 所以你认为你会使用什么hw for - 应该可以帮助您弄清楚堆是如何损坏到运行时系统提示的地步的。

剧透警告(为了获得最佳效果,请在解决问题后阅读):

写在 Mat 的边界之外,因为您从不检查索引的边界以防止它们超出限制,显然 Mat::at 不检查要么(至少,文档没有说它是 - 你可以通过实验来验证)。

关于c++ Floodfill算法在Xcode中崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53323339/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com