Re: *p++ = *q++ undefined? why?



pemo wrote:
pete wrote:
Michael Mair wrote:
pete schrieb:
Vladimir S. Oka wrote:
Eric Sosman opined:
CBFalconer wrote:
pete wrote:

... snip ...

As long as (*p) is defined and (*q) is defined,
there is nothing wrong with (*p++ = *q++).
Assuming p != q.
Even if p == q. (Confession: I very nearly made
the same mistake.)
Now I can see it as well! Apologies for the confusion.

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++)
;
Yes.
/* 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.
Why? How? I cannot see anything undefined in that.
If you wrote "strcpy(char_array + 1, char_array);", then I would
agree.
That's what I meant write.

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.

Because the destination of the assignment is within the source, corrupting it.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
.



Relevant Pages

  • Re: *p++ = *q++ undefined? why?
    ... void strcpy(char *s, char *t) ... int main ... As far as I can see, the assignment expression here will 'run' like ... increment s then t, OR, increment t then s. ...
    (comp.lang.c)
  • Re: *p++ = *q++ undefined? why?
    ... void strcpy(char *s, char *t) ... int main ... increment s then t, OR, increment t then s. ...
    (comp.lang.c)
  • Re: *p++ = *q++ undefined? why?
    ... void strcpy(char *s, char *t) ... increment s then t, OR, increment t then s. ...
    (comp.lang.c)
  • Re: Function pointer tables
    ... I have a table of function pointers, and a function pointer variable p which ... But I'm not allowed to increment the variable using ++p. ... void f1; ... (like stringis char and p must be char *) ...
    (comp.lang.c)
  • [PATCH 2.6.19-rc1 V9] drivers: add LCD support
    ... Adds support for the ks0108 LCD Controller as a device driver. ... +The buffer should be a 128*64 unsigned char array: ... * GNU General Public License for more details. ... +static void cfag12864b_setbit ...
    (Linux-Kernel)