Code Comments
Programming Forum and web based access to our favorite programming groups.<acehreli@gmail.com> wrote in message > On Apr 2, 4:01 pm, Eric Kaplan <tobycraf...@yahoo.com> wrote: > <snip> > 2) String literals are constant objects, which means that the > characters that they contain may not be modified. The fact that it is IIRC, this statement is not true. String literals as defined in the C Standard are not defined as constant. Yet, modifying them leads to undefined behavior. This is what I recollect from C89 (I have to admit that it's been quite some time, so I may be wrong). Most of the Unix compilers place string literals in a read only region, so modifying them gets a segmention violation there. Sharad
Post Follow-up to this messageEric Kaplan wrote:
> why the following code will crash?
>
> int main()
> {
> char* str = "aa";
This is a deprecated conversion from a 3 element array of const char
(holding the values a a and \0) to pointer to (single) character.
> strcat (str, "hello");
This attempts to write hello on to the end of the chars starting
at str. The h is written into read only storage, the ello\0 is
written outside of any allocated memory.
> cout << str << "\n";
> strcat (str, "you1");
> cout << str << "\n";
\
> }
char* is not a string type.
strcat doesn't allocate any memory. You are expected to have enough
allocated memory in the bytes pointed to by the first argument to
hold the concatenation of both strings.
This is C++ and you shouldn't be playing with C's old and busted
string functions but the C++ new hotness string type.
std::string str = "aa";
str += "hello";
cout << str << "\n"
see.
Post Follow-up to this messageSharad wrote: > <acehreli@gmail.com> wrote: > > I don't think so. I will need to go back to the C Standard to verify that. > 2.13.4 of the C++ standard states that a string literal has type "array of n const char". -- Ian Collins.
Post Follow-up to this messageacehreli@gmail.com wrote: > On Apr 2, 4:50 pm, utab <umut.ta...@gmail.com> wrote: > > The OP used 'cout', so I'm assuming this is C++. (Heck, the group is > clc++!) So the compiler is required to reject passing str to strcat > now. ;) > Only if str is "const char*". -- Ian Collins.
Post Follow-up to this message"Ian Collins" <ian-news@hotmail.com> wrote in message news:65inveF2g3gvtU4@mid.individual.net... > Sharad wrote: > > 2.13.4 of the C++ standard states that a string literal has type "array > of n const char". OK thanks!
Post Follow-up to this messageIn article <e8a61d54-c9d0-4c4e-9ba5-65c23159ced5@e6g2000prf.googlegroups.com >, utab <umut.tabak@gmail.com> wrote: > >For the code at hand, this does not help to recover the segfault >though. There won't be any segfault because the code won't compile.
Post Follow-up to this messagePowered by vBulletin
Copyright 2000-2006 Jelsoft Enterprises Limited.