gpt4 book ai didi

ios - 释放结构时出错

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

我是 iOS 开发新手。我在设备上运行此代码然后出错。

/**
* Structure to keep one pixel in RGBA format
*/

struct pixel {
unsigned char r, g, b, a;
};

/**
* Process the image and return the number of pure red pixels in it.
*/

- (NSUInteger) processImage: (UIImage*) image
{
NSUInteger numberOfRedPixels = 0;

// Allocate a buffer big enough to hold all the pixels

struct pixel* pixels = (struct pixel*) calloc(1, image.size.width * image.size.height * sizeof(struct pixel));
if (pixels != nil)
{
// Create a new bitmap

CGContextRef context = CGBitmapContextCreate(
(void*) pixels,
image.size.width,
image.size.height,
8,
image.size.width * 4,
CGImageGetColorSpace(image.CGImage),
kCGImageAlphaPremultipliedLast
);

if (context != NULL)
{
// Draw the image in the bitmap

CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, image.size.width, image.size.height), image.CGImage);

// Now that we have the image drawn in our own buffer, we can loop over the pixels to
// process it. This simple case simply counts all pixels that have a pure red component.

// There are probably more efficient and interesting ways to do this. But the important
// part is that the pixels buffer can be read directly.

NSUInteger numberOfPixels = image.size.width * image.size.height;

while (numberOfPixels > 0) {
if (pixels->r == 255) {
numberOfRedPixels++;
}
pixels++;
numberOfPixels--;
}

CGContextRelease(context);
}

free(pixels);
}

return numberOfRedPixels;
}

错误是:PTP(4821,0x3ece6d98) malloc:* 对象 0x45a9e00 错误:未分配正在释放的指针* 在 malloc_error_break 中设置断点进行调试。

请帮我解决这个错误。非常感谢。

最佳答案

这是一个旧线程,但我想我应该在这里发布一个答案。

错误在 pixels++ 行。正如@Michael 指出的那样,地址在循环内发生了变化。我的解决方案是用以下内容替换整个 while block :

for (int i=0; i<numberOfPixels; i++) {
if (pixels[i].r == 255) {
numberOfRedPixels++;
}
}

干杯!

关于ios - 释放结构时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13872661/

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