2012-12-14 3 views
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에 중단 점을 설정 할당되지 않은 해제된다.

이 오류를 해결하는 데 도움주세요. 감사합니다.

+1

오류가있는 것 같습니다 : pixels ++; –

답변

0

을 호출 한 후 원래 값인 pixels의 포인터를 유지해야합니다. 이 주소는 free으로 전달해야합니다. 루프 내부에서이 주소를 변경하고 있습니다.

+0

내 코드를 바꿀 것입니다 : while (numberOfPixels> 0) { if (pixels-> r == 0 && pixels-> g == 0 && pixels-> b == 0) { numberOfRedPixels ++; } 픽셀 ++; numberOfPixels--; } to : (int i = 0; i

+0

질문에 업데이트를 게시하십시오. 여기를 읽기가 어렵습니다. –

1

이것은 오래된 스레드이지만 여기에 답변을 게시 할 것이라고 생각했습니다.

오류는 픽셀 ++ 행에 있습니다. @Michael이 지적했듯이 주소는 루프 내부에서 변경되고있었습니다. 내 솔루션은 전체 블록을 다음으로 대체하는 것이 었습니다.

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

건배!

관련 문제