Your email has been very helpful to me - thanks again. When I initially copied the program from Herbert Schildes book it didn't seem to 'smell' right, but I pressed on. As you say, a predefined string is obviously a constant - otherwise why predefine it.
The library function strdup() is not mentioned in K&R but strcpy() is - I assume that these are very similar.
There is another question which no doubt you can help on - I have read that the library function 'gets' (defined in K&R) is regarded as dangerous in Linux - is this true?
Also, do you know of an IDE for GCC ( in a similar manner to that provided by Borland C++) ? This would be very useful.
Regards
David
Brett Nash wrote:
Hello David,
main()
{ code("This is a test string");
The argument is a "string literal". Technically it is a "const char *",
not a "char *".
Any attempts to modify the string are "undefined". "Undefined" in C parlance (in this case) means it can have any affect, including crashing the program.
To get the code to work you can set -fwriteable-strings on the compilation line. As the gcc manual says however "Writing into string constants is a very bad idea; ââconstantsââ should be constant".
A quick solution is to make a copy, either by using strdup() or copied
into an array.
Generally I would consider it a bug that it works on any other compilers. ;-)
As an aside, if you don't have a good reference on C, I would suggest hunting down a copy of Brian Kernighan & Dennis Richies "The C Programming Language", a little expensive (~$70) for it's size (250pages), but you won't find a better reference ANYWHERE for C, with the possible exception of the ANSI standard, and K&R is much more readable. The reference manual section will allow you work out such issues very quickly (A2.6 covers string literals, and your specific problem quite concisely - I can post you the section if you wish).
Regards, nash
-- SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/ Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html
