free struct时出错

时间:2012-12-14 04:28:45

标签: ios memory struct

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

请帮我修复此错误。 非常感谢。

2 个答案:

答案 0 :(得分:1)

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

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

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

干杯!

答案 1 :(得分:0)

确保在调用pixels后保留指向calloc原始值的指针。这是您需要传递给free的地址。你正在循环中改变这个地址。