Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Const correctness




On 09.06.2005, at 13:49, Clark Cox wrote:

On 6/9/05, Markian Hlynka <email@hidden> wrote:

And the runtime crash in the above example has absolutely nothing to do with 'const' and everything to do with trying to change an embedded string. I.e. the following crashes exactly the same: char* noConstsAreBetter = "these consts suck\n"; printf( noConstsAreBetter ); noConstsAreBetter[0] = 'T'; printf( noConstsAreBetter );


I seem to recall this is because literals like this are allocated on the heap, not the stack. That's why bad things happen when you try to change it. The heap is not for you. ;-)

This has nothing to do with the heap or the stack. It is simply because the C and C++ standards say that attempting to modify a string literal is undefined behavior.


.. and in this case, you get a kernel exception because the compiler put the string literals into a read-only segment, just like code.
For gcc this is the default, but for other compilers and other platforms this might be different.


You can gcc force to put string literals into a writable segment using option -fwritable-strings (wouldn´t recommend this, though!).

In order to be platform independend, i would recommend to declare string literal const:
const char* cs = "I'm const";
then, you get compiler errors when you attempt to modify the characters.



Andreas Grosam


-- Clark S. Cox III
email@hidden
http://www.livejournal.com/users/clarkcox3/
http://homepage.mac.com/clarkcox3/
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/xcode-users/ email@hidden


This email sent to email@hidden


_______________________________________________ Do not post admin requests to the list. They will be ignored. Xcode-users mailing list (email@hidden) Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/xcode-users/email@hidden

This email sent to email@hidden
References: 
 >Const correctness (From: "Theodore H. Smith" <email@hidden>)
 >Re: Const correctness (From: Cameron Hayne <email@hidden>)
 >Re: Const correctness (From: Keith Ray <email@hidden>)
 >Re: Const correctness (From: Markian Hlynka <email@hidden>)
 >Re: Const correctness (From: Clark Cox <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.