SecItemCopyMatching memory leak

I have a memory leak in the following code. I am inspired here and it is part of the RSA algorithm.

- (SecKeyRef)getPublicKeyRef { OSStatus resultCode = noErr; SecKeyRef publicKeyReference = NULL; if(publicKey == NULL) { NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init]; NSData *publicTag = [NSData dataWithBytes:publicKeyIdentifier length:strlen((const char *)publicKeyIdentifier)]; // Set the public key query dictionary. [queryPublicKey setObject:(id)kSecClassKey forKey:(id)kSecClass]; [queryPublicKey setObject:publicTag forKey:(id)kSecAttrApplicationTag]; [queryPublicKey setObject:(id)kSecAttrKeyTypeRSA forKey:(id)kSecAttrKeyType]; [queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnRef]; // Get the key. resultCode = SecItemCopyMatching((CFDictionaryRef)queryPublicKey, (CFTypeRef *)&publicKeyReference); // NSLog(@"getPublicKey: result code: %d", resultCode); if(resultCode != noErr) { publicKeyReference = NULL; } // [publicTag release]; [queryPublicKey release]; } else { publicKeyReference = publicKey; } return publicKeyReference; 

}

The Leak tool says it flows on this line:

 resultCode = SecItemCopyMatching((CFDictionaryRef)queryPublicKey, (CFTypeRef *)&publicKeyReference); 

Please tell me how I can solve this.

+6
security iphone rsa
source share
1 answer

Your method sometimes returns an instance while keeping count +1, and you most likely don't release it in the rest of your code. You return with saving count +1 if SecItemCopyMatching is called, but if publicKey is set, your function returns a value with saving count + -0, which is bad.

You need to make sure that you always return with the same save account. In this case, I would do:

 } else { publicKeyReference = publicKey; CFRetain(publicKeyReference); } 

Then, each caller of your method must verify the CFRelease value ... but this violates the get rule (it should return the value count + -0), so it might be nice to rename the method.

+6
source share

All Articles