Memory Management: NSString stringWithCString: encoding:

Suppose I get a string C from some function:

char * mystring = SomeCFunction(...);

And I have this line (I am responsible for releasing it when I finished).

If in Objective-C I create an NSString * using:

 NSString * mynsstring = [NSString stringWithCString:mystring encoding:NSUTF8StringEncoding]; 

Am I still responsible for freeing the original C line?

I suppose the answer is yes, but I cannot find the final answer in the documentation - and the functionality of the opposite method ( cStringUsingEncoding ), while sensitive, pauses because it processes cString frees you up.

If the answer is yes, am I also responsible for not releasing the string c before I finish using NSString * , or does the function copy the string for me? I ask for this because the documentation for stringWithCString says:

Returns a string containing bytes in the given array C, is interpreted according to the specified encoding.

Which still leaves me wondering if he really copied bytes or just points to them internally (and I'm just doing actors).

+6
source share
2 answers

It copies bytes.

If you do not want the bytes to be copied, you can use - (id)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length encoding:(NSStringEncoding)encoding freeWhenDone:(BOOL)flag instead - (id)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length encoding:(NSStringEncoding)encoding freeWhenDone:(BOOL)flag .

If you use - (id)initWithBytes:(const void *)bytes length:(NSUInteger)length encoding:(NSStringEncoding)encoding or any product method, for example stringWithCString:encoding: which itself calls this low-level method, bytes are copied.

+8
source

The API does not have a clue where you are passing the pointer to, so it does not know how to take responsibility for this. It can be from malloc (), but it can also be an interior pointer or from mmap (), in which case free () will not work. Therefore, the API is forced to copy data.

The only time you can transfer ownership of the C buffer to the Cocoa API is if the API allows you to say that it needs to be freed. -[NSData initWithBytesNoCopy:length:freeWhenDone:] look -[NSData initWithBytesNoCopy:length:freeWhenDone:] , for example.

+3
source

Source: https://habr.com/ru/post/900076/


All Articles