Re: Highly efficient string reversal code
Lew Pitcher <lpitcher@teksa vvy.comwrites:
Did you not read the thread section where this is UDB in the case of
zero length strings? A surprise to me too I must admit. And thats even
before you use the illegal value in the comparison below.
--
Lew Pitcher <lpitcher@teksa vvy.comwrites:
My contribution to the cause
>
char *reverse(char *str)
{
char *start, *end, temp;
>
for (end=str;*end;+ +end);
--end; /* A */
>
char *reverse(char *str)
{
char *start, *end, temp;
>
for (end=str;*end;+ +end);
--end; /* A */
zero length strings? A surprise to me too I must admit. And thats even
before you use the illegal value in the comparison below.
>
for (start=str; start < end; ++start, --end) /* B */
{
temp = *start;
*start = *end;
*end = temp;
}
return str;
}
>
NB: For the degenerate case of a zero-length string, the computation of the
end character ( /* A */ ) produces a pointer that, *if dereferenced* would
encounter UB because it points out-of-bounds to the intended array.
*However*, the reversal loop ( /* B */ ) tests the value of this pointer
(without dereferencing it), and will discontinue the loop immediately
(again, without dereferencing the pointer).
for (start=str; start < end; ++start, --end) /* B */
{
temp = *start;
*start = *end;
*end = temp;
}
return str;
}
>
NB: For the degenerate case of a zero-length string, the computation of the
end character ( /* A */ ) produces a pointer that, *if dereferenced* would
encounter UB because it points out-of-bounds to the intended array.
*However*, the reversal loop ( /* B */ ) tests the value of this pointer
(without dereferencing it), and will discontinue the loop immediately
(again, without dereferencing the pointer).
Comment