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

Re: Very odd programming trouble



On Tue, Aug 07, 2001 at 03:20:52PM +0100, J.A.Serralheiro wrote:
> /*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 ?

char *s = "whatever";

declares a string constant. As the name 'constant' implies, this is not
modifiable, so the compiler may decide to place it in the code segment
of the program, which is typically flagged read-only.  If you try to
modify that memory location you'll get the segment access violation.

Your options are to use a local variable as the string buffer (which
will reside on the stack), a global variable (data segment) or allocate
memory dynamically from the heap with malloc().

Cheers

-- 
Erdmut Pfeifer
science+computing ag

-- Bugs come in through open windows. Keep Windows shut! --



Reply to: