[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Very odd programming trouble



"J.A.Serralheiro" <mrserra@ci.uc.pt> writes:
> /*Hi folks. Heres a very odd trouble ( for me at least)
>   I was reading a book where it was stated that
>  "     char *ptr = "text";   " is an allowed declaration and that
>   the compiler automatically allocates space for the string text and for the
>   \0 terminating character ( true) . 
>   I decided to try it with strcpy(char *dest, const char *src) and 
>   there seems to be a problem. Whenever dest is a pointer declared as above
>   theres a segmentation fault. I tried the code bellow which suffers from 
>   exactly the same. The problem seems to relly In the expression
>    "while ( (*dest++ = *src++)!= '\0' )" .
> I tried all the combinations with strcpy, but only this one gave odd results.
>   It seems that the compiler as some dificulties assigning *dest++ = *src++
>   when dest is a char *ptr = "kljdflg". But when src is this kind of
> pointer and dest is an array ( as so declared) ,
>   it works fine. Its not very usual to declare strings this way
>   but its stated as ansi compliant, and the compiler silently accepts it
> without any warnings.
>   The code is set to the particular combination where a SIGSEGV is generated
>   dest=s1; /*char *s1 = "ldksj" 
>   src=string; /*char string[]= "dflkjg"*/
> 
> Can someone solve this mistery ?

Yeah. Get a copy of "The C Programming Language" by Kernighan and
Ritchie. If you're going to do any serious C programming and don't
have this little beauty you're asking for trouble.

In that book, 2nd Edition, on page 104 under the section titled
"5.5 Character Pointers and Functions":

<quote>
There is an important difference between these definitions:

        char amessage[] = "now is the time";    /* an array */
        char *pmessage  = "now is the time";    /* a pointer */

"amessage" is an array, just big enough to hold the sequence of
characters and '\0' that initializes it. Individual characters within
the array may be changed but "amessage" will always refer to the same
storage. On the other hand, "pmessage" is a pointer, initialized to
point to a string constant; the pointer may subsequently be modified
to point elsewhere, ****BUT THE RESULT IS UNDEFINED IF YOU TRY TO
MODIFY THE STRING CONTENTS**** </quote>

So what you're doing is undefined according to the standard. Anything
can happen, from a segmentation violation, to a random occurence to
the system allowing you to modify what "pmessage" is pointing to as
you were trying to do.

Think of what "pmessage" is pointing to as a static string constant
that can't be modified. Sort of like a read-only location in memory.

Gary



Reply to: