Mail Archives: djgpp/2001/07/26/11:54:29
> : str="01234";
> : puts(str);
> : printf("%s\n",str);
> : strcat(str,"567");
> : puts(str);
> : printf("%s\n",str);
> : return 1;
>
> : Why this code produces following results?
> : 01234
> : 01234
> : 01234567
> : 67
>
> : Other compilers give me:
> : 01234
> : 01234
> : 01234567
> : 01234567
>
> Only (bad) luck.
Actually, no - it IS odd. With the code he posted, if the strcat does
not cause a segmentation fault, you'd expect the output he posted as
resulting from other compilers; the relevant snippet is:
> : puts(str);
> : printf("%s\n",str);
Regardless of what str points to, neither of these modify str in any
way, so both should print the same value. At the very least,
"012345" should appear; the rest is memory that might have been
changed, as it does not belong to the string constant.
In any case, the solution to the problem is simply to change
str = "01234"
to
strcpy (str, "01234");
(and adding a 'free(str)' at the end).
--
Tim Van Holder - Anubex N.V.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
This message was posted using plain text. I do not endorse any
products or services that may be hyperlinked to this message.
- Raw text -