Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

strcpy(s, s+1) Is Undefined?

1 view
Skip to first unread message

Heartist

unread,
Jun 28, 2001, 6:47:57 AM6/28/01
to
( I have cancelled my message in comp.std.c but for a time, that may be
exist before disappear )


char s[100] = "test string";


strcpy( s, s+1 );

memcpy( s, s+1, 1+strlen(s+1) );


If memory is overlapped,

should I use memmove() ?

I have used memmove(), when src and dest is overlapped and src < dest .

(ex> memmove( s+1, s, strlen(s)+1 )

Joona I Palaste

unread,
Jun 28, 2001, 7:08:06 AM6/28/01
to
Heartist <qw...@hanmail.net> scribbled the following:


> strcpy( s, s+1 );


> If memory is overlapped,

Yes, strcpy() and memcpy() yield undefined behaviour if the source and
destination areas overlap. Your only options are to use memmove(), or to
write the copying logic yourself. It's not too hard, just a bit of
pointer arithmetics.

--
/-- Joona Palaste (pal...@cc.helsinki.fi) ---------------------------\
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
| http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/

"'So called' means: 'There is a long explanation for this, but I have no
time to explain it here.'"
- JIPsoft

Mike Wahler

unread,
Jun 28, 2001, 7:04:11 AM6/28/01
to

Heartist wrote in message <9hf1v4$s1q$1...@news1.kornet.net>...

>( I have cancelled my message in comp.std.c but for a time, that may be
>exist before disappear )
>
>
>char s[100] = "test string";
>
>
>strcpy( s, s+1 );
>
>memcpy( s, s+1, 1+strlen(s+1) );
>
>
>If memory is overlapped,
>
>should I use memmove() ?

Yes.


>I have used memmove(), when src and dest is overlapped and src < dest .
>
> (ex> memmove( s+1, s, strlen(s)+1 )


From ISO/IEC 9899:1999 (E) :

[begin quote]

7.21.2.2 The memmove function

...

Description

2 The memmove function copies n characters from the
object pointed to by s2 into the object pointed to
by s1. Copying takes place as if the n characters
from the object pointed to by s2 are first copied
into a temporary array of n characters that does not
overlap the objects pointed to by s1 and s2, and then
the n characters from the temporary array are copied
into the object pointed to by s1.

.....

7.21.2.3 The strcpy function

...

Description

2 The strcpy function copies the string pointed to by
s2 (including the terminating null character) into the
array pointed to by s1. If copying takes place between
objects that overlap, the behavior is undefined.

[end quote]

-Mike

0 new messages