I write the AES256Decrypt method using objective-c.
But When I return the decrypt NSData , the memory is not release ,
my code below:
- (NSData*)AES256DecryptWithKey:(NSString*)key andIv:(NSData*)iv{
char keyPtr[kCCKeySizeAES256 + 1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
iv.bytes /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesDecrypted);
if (cryptStatus == kCCSuccess)
{
// ==============here==============
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted freeWhenDone:YES];
}
free(buffer); //free the buffer;
return nil;
}
I found cryptStatus == kCCSuccess status,
it return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted freeWhenDone:YES];
the code not free(buffer);
If I move the free(buffer) up to
[NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted freeWhenDone:YES];
The buffer data will release so early.
How can I cost down the memory to prevent the memory leak in the decrypt method?
thank you very much.