|> When I compile this code, I get a segmentation fault on my UNIX box:
|> char* p = "Hi";
|> *p = 'p';
|> Is the reason because "Hi" is a constant literal?
|> (Someone compiled this with a C compiler and there were no errors)
|> Thanks GUYS/GALS!
|> Right. This is the reason that, for a while, strings were of type
|> const char *.
Literal strings have never had the type "const char*" (or "const
char[]). Literal strings *are* unmodifiable. Any attempt to modify a
literal string results in undefined behavior.
|> This has been changed (I believe) since too many error
|> messages ensued because lazy people were not using const char *
|> pointers whenever they did not need to change anything (underuse of
|> constness is still a very popular programming mistake.
When literal strings were made unmodifiable (in the C standard), const
didn't exist (or hadn't existed before), so it is not surprising that
people didn't use it. Believe it or not, there are still C compilers
delivered today that don't support const.
You are correct in stating that the reason a string literal doesn't have
the type "const char[]" is that it would break such code. Given that
such code was written before const was added to the language, however, I
don't think you can accuse the programmers of laziness for not using it.
Quote:Adelsberger) writes:
|> > char* p = "Hi";
|> This line creates a character pointer, creates a temporary character array
|> somewhere in memory (in which it stores {'H','i','\0'}), points p to that
|> temporary array, then releases the temporary array as the compiler no longer
|> thinks it is needed. So, p now points to some arbitrary location in memory
|> which, depending on how your system manages memory, may not belong to your
|> program anymore and certainly has undefined contents in the context of your
|> program.
This is completely wrong. Literal strings have static duration: they
exist during the entire lifetime of the program.
|> > *p = 'p';
|> This one tries to write to that arbitrary location in memory I was just
|> talking about, and so it seg faults.
More likely: the compiler allocated the string in write protected memory
(since it is unmodifiable). Writting to write protected memory will
generally cause a core dump.
|> If you actually have a use for this, try something like:
|> char p[3] = "Hi"; //actually gives you the memory in question
|> *p = 'p'; //not the best form, but will work.
Without the static, this is actually worse than the original. This
*does* allocate memory which is released.
You might want to try:
static char buffer[] = "Hi" ;
p = buffer ;
// ...
This results in p pointing to a modifiable string.
--
GABI Software, Sarl., 8 rue des Francs Bourgeois, 67000 Strasbourg, France
Conseils en informatique industrielle --
-- Beratung in industrieller Datenverarbeitung
[ about comp.lang.c++.moderated. First time posters: do this! ]