1

我是初学者开发者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 中设置断点以进行调试。

请帮我解决这个错误。太感谢了

4

2 回答 2

1

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

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

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

干杯!

于 2013-12-27T19:48:25.100 回答
0

pixels确保在调用后维护指向原始值的指针calloc。这是您需要传递到的地址free。您正在循环内更改此地址。

于 2012-12-14T05:11:18.680 回答