Re: *p++ = *q++ undefined? why?
- From: pete <pfiland@xxxxxxxxxxxxxx>
- Date: Mon, 03 Apr 2006 13:18:24 GMT
Bas Wassink wrote:
pete wrote:
pete wrote:
Joe Wright wrote:
pemo wrote:
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.
Specifically, the null characters are being overwritten,
and the loop never ends.
There's also a reserved identifier problem,
but that's another story.
From what I can see there's no UB here, since it's not the standard
library function strcpy,
which is indeed said to behave undefined if the
objects overlap.
This function is (apart from using a reserved identifier) perfectly
valid. Even swapping the arguments would still make this code valid,
although the behaviour of the
function might not be what one would want.
Specifically, the null characters are being overwritten,
and the loop never ends.
The loop attempts to overwrite memory beyond the bounds
of the array, that's undefined behavior.
You can try running the program
if you feel like risking the consequences.
I've noticed that nobody has said
that they've run the program.
--
pete
.
- 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?
- From: Joe Wright
- Re: *p++ = *q++ undefined? why?
- From: pete
- Re: *p++ = *q++ undefined? why?
- From: pete
- Re: *p++ = *q++ undefined? why?
- From: Bas Wassink
- Re: *p++ = *q++ undefined? why?
- Prev by Date: Re: variable declaration in for()
- 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
|