CFString 内存泄漏 [英] CFString memory leak
问题描述
我已将内存泄漏范围缩小到以下代码
I have narrowed down a memory leak to the following code
CFStringRef CFDataToString(CFDataRef data)
{
UInt8* buf = malloc(CFDataGetLength(data));
CFDataGetBytes(data, CFRangeMake(0, CFDataGetLength(data)), buf);
CFMutableStringRef output = CFStringCreateMutable(kCFAllocatorDefault, CFDataGetLength(data) * 2);
for(int i = 0; i < CFDataGetLength(data); i++) {
CFStringAppendFormat(output, NULL, CFSTR("%02x"), buf[i]);
}
free(buf);
CFRelease(data);
return output;
}
以下是上下文中使用的代码,为了演示,已经简化了一些方法.Instruments 报告了 CFStringCreateMutable 和 CFStringAppendFormat 的内存泄漏.
Below is the code used in context, some methods has been simplified for demonstration. Instruments is reporting a memory leak of CFStringCreateMutable and CFStringAppendFormat.
CFStringRef CFDataToString(CFDataRef data)
{
UInt8* buf = malloc(CFDataGetLength(data));
CFDataGetBytes(data, CFRangeMake(0, CFDataGetLength(data)), buf);
CFMutableStringRef output = CFStringCreateMutable(kCFAllocatorDefault, CFDataGetLength(data) * 2);
for(int i = 0; i < CFDataGetLength(data); i++) {
CFStringAppendFormat(output, NULL, CFSTR("%02x"), buf[i]);
}
free(buf);
CFRelease(data);
return output;
}
CFDataRef hmac(CFStringRef key, CFStringRef data)
{
const char *cKey = CFStringGetCStringPtr(key, CFStringGetSystemEncoding());
const char *cData = CFStringGetCStringPtr(data, CFStringGetSystemEncoding());
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
CFDataRef HMAC = CFDataCreate(kCFAllocatorDefault, cHMAC, sizeof(cHMAC));
return HMAC;
}
CFDictionaryRef buildRequest(CFMutableDictionaryRef params)
{
CFMutableStringRef signature = CFStringCreateMutable(NULL, 0);
CFStringAppend(signature, CFDataToString(hmac(CFSTR("mykey"), CFSTR("mydata"))));
CFDictionarySetValue(params, CFSTR("signature"), signature);
// ....
// ....
return params;
}
void request(CFMutableDictionaryRef params)
{
params = buildRequest(params);
// ... Run request
CFRelease(params);
}
仪器输出...
推荐答案
再次作为答案.
使用 Create
方法分配的所有数据都负责将数据发布给程序员.在这方面,它与调用 malloc
相同.除非在文档中明确说明,否则任何方法都不会发布这些数据.
All data allocated with a Create
method puts the responsibility for releasing the data to the programmer. In this regard, it's the same as calling malloc
. No method will ever release this data, unless explicitely stated in the documentation.
要解决您的问题,请在接收它的方法中保存对已创建"(已分配)数据的引用,并在完成后在方法结束时释放它.
To solve your problem, save a reference to the 'Created' (Allocated) data in the method which receives it and release it at the end of the method, once you're done with it.
这篇关于CFString 内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!