Re: *p++ = *q++ undefined? why?
- From: Joe Wright <joewwright@xxxxxxxxxxx>
- Date: Sun, 02 Apr 2006 11:27:07 -0400
pemo wrote:
pete wrote:Because the destination of the assignment is within the source, corrupting it.Michael Mair wrote:pete schrieb:That's what I meant write.Vladimir S. Oka wrote:Why? How? I cannot see anything undefined in that.Eric Sosman opined:Yes.CBFalconer wrote:Now I can see it as well! Apologies for the confusion.pete wrote:Even if p == q. (Confession: I very nearly made
... snip ...
As long as (*p) is defined and (*q) is defined,Assuming p != q.
there is nothing wrong with (*p++ = *q++).
the same mistake.)
Now that I actually thought it through, isn't the above the very
construct K&R use to implement `strcpy()`? I left my copy at work, so
I can't look it up, but I'm pretty sure. Along the lines of:
while (*p++ = *q++)
;
/* strcpy: copy t to s; pointer version 3 */
void strcpy(char *s, char *t)
{
while (*s++ = *t++)
;
}
You can see how that implementation of strcpy
would be undefined with something like:
char char_array[] = "xx\0";
strcpy(char_array, char_array + 1);
though
memmove(char_array, char_array + 1, 1 + strlen(char_array + 1));
would be fine.
If you wrote "strcpy(char_array + 1, char_array);", then I would
agree.
I must be going mad, or missing something here - are you saying that
the code below gives UB?
#include <stdio.h>
void strcpy(char *s, char *t)
{
while(*s++ = *t++)
;
}
int main(void)
{
char char_array[] = "xx\0";
strcpy(1 + char_array, char_array);
return 0;
}
If 'yes', can you explain why please.
while(*s++ = *t++)
As far as I can see, the assignment expression here will 'run' like
this:
1. eval *t
2. take value found in '1' - write to *s
3. increment s then t, OR, increment t then s.
4. repeat.
--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
.
- Follow-Ups:
- Re: *p++ = *q++ undefined? why?
- From: pete
- Re: *p++ = *q++ undefined? why?
- References:
- Re: *p++ = *q++ undefined? why?
- From: Vladimir S. Oka
- Re: *p++ = *q++ undefined? why?
- From: Michael Mair
- Re: *p++ = *q++ undefined? why?
- From: pete
- Re: *p++ = *q++ undefined? why?
- From: CBFalconer
- Re: *p++ = *q++ undefined? why?
- From: Eric Sosman
- Re: *p++ = *q++ undefined? why?
- From: Vladimir S. Oka
- Re: *p++ = *q++ undefined? why?
- From: pete
- Re: *p++ = *q++ undefined? why?
- From: Michael Mair
- Re: *p++ = *q++ undefined? why?
- From: pete
- Re: *p++ = *q++ undefined? why?
- From: pemo
- Re: *p++ = *q++ undefined? why?
- Prev by Date: Re: convert int to store in binary file in 1byte
- Next by Date: Re: *p++ = *q++ undefined? why?
- Previous by thread: Re: *p++ = *q++ undefined? why?
- Next by thread: Re: *p++ = *q++ undefined? why?
- Index(es):
Relevant Pages
|
|