Question

Possible Duplicate:
Why does simple C code receive segmentation fault?

Why code snippet 2 doesn't behave like snippet 1?

//Code snippet 1
char pstr[] = "helloworld";
char *p = pstr; 
p[2] = 'd';

//Code snippet 2
char *p = "helloworld";
p[2] = 'd'; //error: access violation

P.S Forgive my ignorance.

Was it helpful?

Solution

"helloworld" is an array of const char. There's a hole in the type system which allows you to point to it with a char*, because a lot of code exists which uses a char * to point to readonly data and this is safe.

But const_cast rules apply, you can't actually write to the const data even if you make a non-const pointer to it.

OTHER TIPS

The first snippet creates an array of char and initializes its contents to "helloworld". Then you change its third element.

The second one simply creates a pointer to char that points to a string literal. Then you attempt to change the third character of that literal. String literals are not writable in code produced by many modern compilers.

EDIT:

GCC used to have an -fwritable-strings option that enabled string literals to be writable, since there is legacy code around that depends on this behaviour. That option was removed in the GCC 4.0 release series.

It would help if you could tell us in what way they're behaving differently.

But as a guess, I think your problem is that the second form has 'p' pointing to a string in read-only memory. Attempts to write through the pointer 'p' would result in a program failure.

I can tell you that the Gnu c++ compiler will warn you about this.

I'm guessing when you say "doesn't behave like" you mean one throws an illegal access exception (or something similar) while the other gives a compile time warning or error?

The answer is that in the first case, you're creating a pointer to your own memory, and copying the c9ontents into it. At that point the compiler forgets it used to be a pointer to static memory; the run time system, however, doesn't forget.

In the other case, the compiler "knows" p is a pointer to static memory, and so has the chance to say "whoa, dude, can't do that".

But this is a bit of a guess without knowing exactly what it does differently. it's also going to be compiler and implementation dependent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top