gpt4 book ai didi

objective-c - iPhone 泛洪内存泄漏

转载 作者:行者123 更新时间:2023-11-30 15:51:15 24 4
gpt4 key购买 nike

我正在用 C 语言为 iPhone 实现一个 floodfill 函数。

填充有效,尽管我遇到了 2 个问题。

  1. 执行几次以下代码后,手机会发出内存警告。最有可能是内存泄漏。另请注意,unsigned char *data (图像数据)在洪水填充结束时被释放。

  2. (较小的问题)如果我尝试将 RGB 颜色写入大于大约 (r:200,g:200,b:200,a:200 ) 我遇到了奇怪的现象。解决此问题的方法是简单地限制值。

我怀疑这两个问题之间可能存在关联。

下面的代码使用堆栈描述了我的洪水填充算法:

.h:

typedef struct {
int red;
int green;
int blue;
int alpha;
} GUIColor;


struct pixel_st {
int x;
int y;
struct pixel_st *nextPixel;
};
typedef struct pixel_st pixel;

.m:

   void floodFill(CGPoint location, GUIColor tc, GUIColor rc, size_t width, size_t height, unsigned char *data){
if (isGUIColorEqual(tc, rc)) return;

pixel* aPixel = (pixel *) malloc(sizeof (struct pixel_st));
NSLog(@"sizeof aPixel : %i",(int)sizeof(aPixel));

(*aPixel).x = location.x;
(*aPixel).y = location.y;
(*aPixel).nextPixel = NULL;

int i = 0;

NSLog(@"Replacement color A%i, R%i, G%i, B%i",rc.alpha,rc.red,rc.green, rc.blue);

while (aPixel != NULL){
pixel *oldPixel_p = aPixel;
pixel currentPixel = *aPixel;
aPixel = currentPixel.nextPixel;


//Now we do some boundary checks
if (!isOutOfBounds(currentPixel.x, currentPixel.y, width, height)){
//Grab the current Pixel color
GUIColor currentColor = getGUIColorFromPixelAtLocation(CGPointMake(currentPixel.x, currentPixel.y), width, height, data);

if (isGUIColorSimilar(currentColor, tc)){
//Colors are similar, lets continue the spread
setGUIColorToPixelAtLocation(CGPointMake(currentPixel.x, currentPixel.y), rc, width,height, data);

pixel *newPixel;


if ((newPixel = (pixel*) malloc(sizeof(struct pixel_st))) != NULL) {
(*newPixel).x = currentPixel.x;
(*newPixel).y = currentPixel.y-1;
(*newPixel).nextPixel = aPixel;
aPixel = newPixel;

}
if ((newPixel = (pixel*) malloc(sizeof(struct pixel_st))) != NULL) {
(*newPixel).x = currentPixel.x;
(*newPixel).y = currentPixel.y+1;
(*newPixel).nextPixel = aPixel;
aPixel = newPixel;
}
if ((newPixel = (pixel*) malloc(sizeof(struct pixel_st))) != NULL) {
(*newPixel).x = currentPixel.x+1;
(*newPixel).y = currentPixel.y;
(*newPixel).nextPixel = aPixel;
aPixel = newPixel;
}
if ((newPixel = (pixel*) malloc(sizeof(struct pixel_st))) != NULL) {
(*newPixel).x = currentPixel.x-1;
(*newPixel).y = currentPixel.y;
(*newPixel).nextPixel = aPixel;
aPixel = newPixel;
}
free(oldPixel_p);
i ++;
if (i == width * height * 4 * 5) break;

}


}
}

free(aPixel);
}

此堆栈的实现基于此处找到的 ObjFloodFill:

https://github.com/OgreSwamp/ObjFloodFill/blob/master/src/FloodFill.m

最佳答案

首先,循环内的每个 if ((newPixel = (pixel*) malloc(...) 都会分配新的内存块,因此,您有 4 次分配在循环内并且仅1释放。

其次,我不明白为什么不简单地使用堆栈上的对象?您真的需要在上分配newPixeloldPixel等吗?检查实现,可能有更简单的方法来实现相同的功能,而且根本不需要管理内存问题。

关于objective-c - iPhone 泛洪内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15268098/

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