Question

I'm looking at some code that creates a mutable data object and puts a SHA1 hash into it. If I initialize the target mutable data object with

CFMutableDataRef hashDataRef = (CFMutableDataRef)[[NSMutableData alloc] initWithLength:SHA_DIGEST_LENGTH];

everything works fine. If I change that one line to

CFMutableDataRef hashDataRef = CFDataCreateMutable(kCFAllocatorDefault, SHA_DIGEST_LENGTH);

it breaks (the mutable data object appears to still be empty after the SHA1 command). In both cases, the line that follows the creation of hashDataRef is

SHA1(CFDataGetBytePtr(inputDataRef), CFDataGetLength(inputDataRef), CFDataGetMutableBytePtr(hashDataRef));

I hadn't expected there to be any difference between the two, but clearly I'm missing something. Is there a proper Core Foundation way to get the mutable data object I want without using NSMutableData and toll-free bridging?

Was it helpful?

Solution

NSMutableData initWithLength: creates a data object whose raw data is filled with zeros, but CFDataCreateMutable creates an empty CFMutableDataRef. Even though it was created with a capacity, its length is still zero. So, when you use CFDataGetMutableBytePtr, it returns a NULL pointer.

To fix it, you could fill the CFMutableDataRef to its capacity using CFDataSetLength, which fills the data with zeros.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top