0

I'm trying to create a new CFStringRef from a const char* at runtime, but CFStringCreateWithCString returns null for all strings shorter than 10 characters:

// Test w/ 9-character string
CFStringRef str1 = CFStringCreateWithCString(NULL, "123456789", kCFStringEncodingUTF8);
printf("str1: %p - %s\n", str1, CFStringGetCStringPtr(str1, kCFStringEncodingUTF8));

// Test w/ 10-character string
CFStringRef str2 = CFStringCreateWithCString(NULL, "0123456789", kCFStringEncodingUTF8);
printf("str2: %p - %s\n", str2, CFStringGetCStringPtr(str2, kCFStringEncodingUTF8));

Output of above example:

str1: 0x1ea1f72bb30ab195 - (null)
str2: 0x1005073e0 - 0123456789

As you can see, the first string (consisting of 9 characters) returns null, while the second one (10 characters) works fine.

I made some tests and it seems like CFStringCreateWithCString works fine for all strings with more than 10 characters, but always returns null for strings with 9 or less.

What could cause this behavior and how can I fix it?

lukas
  • 2,300
  • 6
  • 28
  • 41
  • 1) [This](http://stackoverflow.com/q/9166291/2410359) may help 2) Best to insure matching specifier and type `printf("str1: %p - %s\n", (void*)str1, CFS...)` add cast. – chux - Reinstate Monica Apr 21 '17 at 19:47

1 Answers1

0

CFStringCreateWithCString works fine for both strings. The documentation of CFStringGetCStringPtr says:

Quickly obtains a pointer to a C-string buffer containing the characters of a string in a given encoding.

This function either returns the requested pointer immediately, with no memory allocations and no copying, in constant time, or returns NULL. If the latter is the result, call an alternative function such as the CFStringGetCString function to extract the characters.

Whether or not this function returns a valid pointer or NULL depends on many factors, all of which depend on how the string was created and its properties. In addition, the function result might change between different releases and on different platforms. So do not count on receiving a non-NULL result from this function under any circumstances.

Community
  • 1
  • 1
Willeke
  • 14,578
  • 4
  • 19
  • 47