Strange C string and NSString comparison problem

Pay attention to the following code:

NSString *string = @"ä";
const char *str1 = [string cStringUsingEncoding:NSUTF8StringEncoding];
const char *str2 = "ä";
NSLog(@"C string comparison: %d",strcmp(str1,str2));
NSLog(@"str1: \"%s\"", str1);
NSLog(@"str2: \"%s\"", str2);

When launched from a completely new Foundation project, this program outputs:

C string comparison: 0
str1: "√§"
str2: "√§"

This is really what I expect, because the lines should be the same.

However, if I run this exact code somewhere deep in a different code base, I get this output:

C string comparison: 31
str1: "√§"
str2: "√§"

What can explain this difference? I am sure that both files are in UTF-8 encoding. These are different file encodings - the only possible explanation for this behavior, right?

Any ideas what could go wrong in the second case? How can i fix this?

(Perhaps it is worth mentioning that in the second case, the code runs in a file .mm, i.e. under Objective-C ++. Could this be an explanation for this?)

+3
3

- . , , . GCC UTF-8, -finput-charset=<charset>. , Clang .

Xcode . , , , .

GCC . . . -fexec-charset=<charset>.

, . , . , - .

, "ä" Unicode. A (U + 00E4), A (U + 0061), (U + 0308). UTF-8 0xC3 0xA4 0x61 0xCC 0x88. -, , ( : C string, NSString, , NSString -compare:..., NSLiteralSearch , -isEqual... ). , , -.

, , . , . , (, , , ), , .

0

Documentation:

C , , , , , .

I think that in your case either the recipient is freed or the current pool of auto resources is empty.
for instance

NSString *string = @"ä";
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
const char *str3 = [string cStringUsingEncoding:NSUTF8StringEncoding];
[pool release];
NSLog(@"str1: \"%s\"", str3);
const char *str2 = "ä";
NSLog(@"C string comparison: %d",strcmp(str3,str2));
NSLog(@"str2: \"%s\"", str2);  

Output

2012-05-22 17:14:50.069 test[32895:a0f] str1: "√§"
2012-05-22 17:14:50.071 test[32895:a0f] C string comparison: -195
2012-05-22 17:14:50.074 test[32895:a0f] str2: "√§" 



NSString *string = @"ä";
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
const char *str3 = [string cStringUsingEncoding:NSUTF8StringEncoding];
[pool release];
const char *str2 = "ä";
NSLog(@"C string comparison: %d",strcmp(str3,str2));
NSLog(@"str1: \"%s\"", str3);
NSLog(@"str2: \"%s\"", str2);

Output

2012-05-22 17:19:13.226 test[33153:a0f] C string comparison: 0
2012-05-22 17:19:13.228 test[33153:a0f] str1: ""
2012-05-22 17:19:13.229 test[33153:a0f] str2: "√§"
0
source

All Articles