2012-12-14 34 views
1

我是初学者开发人员iOS。 我在设备上运行此代码,然后错误。空闲时出错struct

/** 
* 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设置断点调试。

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

+1

我认为错误来自:像素++; –

回答

0

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

+0

我正在更改我的代码: while(numberOfPixels> 0)if(pixels-> r == 0 && pixels-> g == 0 && pixels-> b == 0)numberOfRedPixels ++; } 像素++; numberOfPixels--; } to:for(int i = 0; i

+0

请在您的问题中发布更新。这在这里很难阅读。 –

1

这是一个古老的线程,但我想我会在这里发表一个答案。

的错误是在像素++线。正如@迈克尔指出的那样,地址在循环内部发生了变化。我的解决方案是用以下代码替换整个块:

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

干杯!