【问题标题】:iOS - Receive Memory Warning, All Malloc's Are FreediOS - 收到内存警告,所有 Malloc 都被释放
【发布时间】:2013-03-07 16:24:02
【问题描述】:

我正在编写一个应用程序,该应用程序需要我存储来自设备摄像头的像素数据并将像素与之前的视频帧进行比较。

这是给我带来问题的方法:

-(UIImage *)detectMotion:(CGImageRef)imageRef
{
    UIImage *newImage = nil;

    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = malloc(height * width * 4);
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent,     bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);

    // this is the problem loop
    for(int i = 0; i < width * height * 4; i += 4) {

        int gray = 0.216 * rawData[i] + 0.715 * rawData[i + 1] + 0.0722 * rawData[i + 2];

        rawData[i] = gray;
        rawData[i + 1] = gray;
        rawData[i + 2] = gray;
        rawData[i + 3] = 255;

        int grayDelta = abs(gray - prevFrameRawData[i / 4]);

        int newColor = 0;
        if (sqrt(grayDelta * grayDelta * 2) >= 60) {
            newColor = 255;
        }

        rawData[i] = newColor;
        rawData[i + 1] = newColor;
        rawData[i + 2] = newColor;
        rawData[i + 3] = 255;

        prevFrameRawData[i / 4] = gray;
   }

   CGImageRef newCGImage = CGBitmapContextCreateImage(context);
   newImage = [UIImage imageWithCGImage:newCGImage];
   CGImageRelease(newCGImage);

   CGContextRelease(context);

   free(rawData);
}

注意:prevFrameRawData 在类的 init 方法中 malloc'd,然后在 dealloc 方法中释放。

在做了一些测试后,我发现如果我没有为内存块分配任何值,我不会收到警告。

我认为当你分配一个像这样的值时

 rawData[i] = value

它只是覆盖了内存中的那个位置。

所有这些低级c的东西对我来说都是新的,希望你们能提供帮助。

【问题讨论】:

  • 你用过静态分析仪吗?它非常擅长发现这样的事情。只需点击“分析”而不是“运行”。
  • 您遇到的具体问题是什么?
  • 应用程序不断关闭,因为它收到内存警告。我不确定是什么导致了警告。

标签: ios malloc memory-warning


【解决方案1】:

原来我们在另一个方法中创建了一个额外的 CGImageRef。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 2021-03-09
    • 1970-01-01
    • 2013-03-05
    • 2020-12-24
    • 2011-04-30
    • 1970-01-01
    相关资源
    最近更新 更多