On Apr 3, 2009, at 19:32, Dave Keck wrote:

As for read-only address space, does the const declaration not take care of
that? (Serious question.)

I just tested whether it's possible to write at the address of an
NSString declared with either:

NSString *const HelloString = @"ABC123";
#define GoodbyeString @"XYZ345"

(If you're interested, you can download my test project here:
http://www.docdave.com/halla.zip)

In both cases, I was able to write to the address of the string
without crashing. I found this surprising, because I assumed at least
HelloString would be stored in the read-only _TEXT segment...

Assuming I've got my const's straight, "NSString *const" makes the pointer const, but not the thing pointed to -- "const NSString *const" would make the pointer *and* the value const, but I doubt the compiler actually has the concept of const-ness of objects. (And NSString's immutability is a run-time thing.)

The object address you used in your test was the NSString instance's address, not the address of the actual characters. What you actually clobbered, if I read it right, is the instance's isa pointer. It's still possible that the C-string is somewhere readonly, and is converted to something at run-time (e.g. UTF-8) or it's possible that the NSString implementation refers to the C-string internally without conversion.

Anyway, that's all about implementation, and there may be multiple implementations, depending on the string's content, or the way it's used. All I was trying to say earlier was that I'm happy enough to take whatever the compiler chooses to do.

If in fact there's any reason to follow Apple's quoted recommendation against the #define approach to string literals, I'd love to hear it. Type safety isn't a consideration, I think, because @"..." is unambiguous as to type. (Well, maybe ambiguous as to const-ness, I don't know.)


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to