Re: char *

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



"Carmen Sei" <fatwallet951@xxxxxxxxx> wrote in message
news:r4gdv3lrrv3s93fr20mtnb5u6rsk0sj5n8@xxxxxxx
why the following compile is OK

but will crash when execute?

String literals (like "abcd") should not be modified. VC compiler
actually stores them in a block of memory marked read-only, so any
attempt to modify them generates a hardware exception (what you call a
crash).

For backward compatibility with C, a string literal (whose type,
formally, is an array of const char) can be implicitly converted to
char*, which gives a false impression that it can in fact be written to.
It can't. Don't do that.

String literals should not be confused with a special form of
initializer that can be used for char arrays:

char* p = "abcd"; // string literal
char arr[] = "abcd"; // initializer

The latter is simply a more compact form of this equivalent statement:

char arr[] = {'a', 'b', 'c', 'd', '\0'};

Character arrays can of course be modified (whether initialized with
what looks like a string literal but isn't, or otherwise).
--
With best wishes,
Igor Tandetnik

With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925


.



Relevant Pages

  • Re: C Strings
    ... I thought string literals were arrays until you operated on them, ... int main ... char *p1; ...
    (comp.lang.c)
  • Re: Sort of mystified from an earlier thread
    ... pete wrote: ... >> char * in c. ... > You do realise that string literals represent arrays of char ... I do realize string literals represent array of chars. ...
    (comp.lang.c)
  • Re: Where can I find more about string literals?
    ... assigned to a variable of type "char *"? ... faq, ... The contents of the arrays are modifiable. ... Try 6.4.5 String literals, p6 "...If the program attempts to modify ...
    (comp.lang.c)
  • Re: VC++ 2005 /Tp /Tc difference.
    ... int main ... I'm surprised your program doesn't crash right here. ... String literals are immutable, and are indeed stored by the compiler in ... With sufficient thrust, pigs fly just fine. ...
    (microsoft.public.vc.language)
  • Re: Pointers and Arrays in C
    ... String literals are statically allocated, so a pointer to one is safe. ... declare it char *. ... The above is okay, but you cannot modify the string, so ... making your pointers const char * would be better. ...
    (alt.comp.lang.learn.c-cpp)