0

我写了这段代码:

 bitmapData = calloc(1, bitmapByteCount );
 context = CGBitmapContextCreate (bitmapData,
                                 pixelsWide,
                                 pixelsHigh,
                                 8,
                                 bitmapBytesPerRow,
                                 colorSpace,
                                 kCGImageAlphaOnly);

当我这样做时,CGBitmapContext 是在复制我的 bitmapData,所以在这些行之后我应该写

free(bitmapData); 
4

2 回答 2

5

如果你需要bitmapData不要释放它。如果您不需要它,请NULL改为作为参数传递,Quartz 将自行分配内存(iOS 4.0 及更高版本)。

data: A pointer to the destination in memory where the drawing is to be rendered. The size of this memory block should be at least (bytesPerRow*height) bytes. In iOS 4.0 and later, and Mac OS X v10.6 and later, you can pass NULL if you want Quartz to allocate memory for the bitmap. This frees you from managing your own memory, which reduces memory leak issues.

But Quartz doesn't copy bitmapData, it does the rendering there. After you release context you should free that memory.

Edit: In one of Apple sample projects, memory is freed, but not immediately:

float drawStage3(CGContextRef context, CGRect rect)
{
    // ...
    cachedData = malloc( (((ScaledToWidth * 32) + 7) / 8) * ScaledToHeight);
    // ...
    bitmapContext = CGBitmapContextCreate(cachedData /* data */,
    // ...
    CFRelease(bitmapContext);
    // ...
    // Clean up
    CFRelease(cachedImage);
    free(cachedData);
}
于 2012-02-25T13:35:14.350 回答
1

编辑:

您的代码正在通过calloc分配一块内存- 您拥有该内存块。所以,你拥有释放那段记忆。CGBitmapContext create 只是使用您创建的内存块创建一个上下文(这就是您必须将其传入的原因)。当你用完那块内存时,你应该释放它。

我会先在上下文中做 CFRelease。上下文创建的任何资源都将由 CFRelease 处理。

Core Foundation Memory Guide中的“创建规则”说:

Core Foundation 函数的名称表明您何时拥有返回的对象:

在名称中嵌入“创建”的对象创建函数;名称中嵌入了“复制”的对象复制函数。如果您拥有一个对象,您有责任在完成该对象后放弃所有权(使用 CFRelease)。

于 2012-02-25T13:13:41.397 回答