我缩小了内存泄漏下面的代码
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;
}
以下是在上下文中使用的代码,有些方法已经被简化为示范。 仪器是报告CFStringCreateMutable和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);
}
仪器输出...