Reputation: 408
I need to compute a signature (a kind of a hash) for my object. The computation requires many per-character operations, so to speed this procedure up, my code operates on CString, and after that converts computed CString to final NSString. The stub code looks like this:
- (NSString *)signature
{
NSString *signatureString = @"?";
char *buffer;
buffer = malloc(sizeof(char)*(self.hashLength+1));
if ( buffer ) {
// Code computing a signature into the buffer
signatureString = [NSString stringWithCString:buffer
encoding:NSASCIIStringEncoding];
free(buffer);
}
return signatureString;
}
I expected that upon creation of NSString characters from source CString are copied into internal structure of NSString object. However in runtime I am getting the error:
malloc: *** error for object 0x8f734d4: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
This looks like chars are not copied, but used from their original memory location. Is it really so? Does it mean that I need to not free allocated memory? Will the NSString deallocate that CString memory upon object destruction?
I can not find any documentation explaining that issue, but because I want to avoid memory leak obviously, I would prefer to be sure,
Upvotes: 2
Views: 1483
Reputation: 408
So the answer is:
Yes, [NSString stringWithCString:encoding:] does copy the source CString to it's internal structure. If the source CString was allocated on a memory heap, it can be freed immediately after NSString object creation.
The error message I got, was caused be a bug inside signature computing code. Due to a wrongly initialized index variable in a for loop, code was writing beyond the allocated memory.
Upvotes: 1
Reputation: 112857
Use a different encoding.
NSASCIIStringEncoding
DOcs state:
Strict 7-bit ASCII encoding within 8-bit chars; ASCII values 0…127 only.
NSMacOSRomanStringEncoding
is a good choice because it handles all 8-bit values.
Upvotes: 0