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



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
.



Relevant Pages

  • Re: Store multiple values in a variable
    ... Joe wrote: ... populated based on the criteria in the procedure but the thing is since ... You are about to overwrite an existing table: ... LOOP -- if overlap exists ...
    (comp.databases.oracle.tools)
  • Re: Deleting a file off a Drive, beyond kill
    ... I found this on Planet Source Code. ... that the binary read in vb6 grabs the exact bytes and the binary ... Dim i As Integer 'variable For times To overwrite ... Next i 'stop Loop ...
    (microsoft.public.dotnet.languages.vb)
  • Store multiple values in a variable
    ... populated based on the criteria in the procedure but the thing is since ... You are about to overwrite an existing table: ... Custom Dayparts 2006 upfront Enhancement. ... LOOP -- if overlap exists ...
    (comp.databases.oracle.tools)
  • Re: Restarting a service - help a noob day!
    ... >> Trying to write a vbs to add a printer then stop and restart the spool ... Is there a better way Do loop until maybe. ... >> Pete. ... > If nLoopCount> nLoopMax Then ...
    (microsoft.public.scripting.vbscript)
  • Re: mail () breaks loop
    ... > Does this call to $db overwrite the result set you are looping on - the ... > you initialise with query? ... This is a query request inside the first loop... ...
    (comp.lang.php)