C
CBFalconer
pete said:Gregory said:There has to be a null terminator somewhere.
Here's a short implementation:
#include <string.h>
size_t (strlen)(char *s)
{
char *p = s;
while (*p != '\0')
p++;
return (size_t)(p - s);
}
The ptrdiff_t type of (p - s) disqualifies this code
from being an example of portable C code.
If the following description of undefined behavior doesn't
apply to your code, then it doesn't apply to anything.
N869
6.5.6 Additive operators
[#9] When two pointers are subtracted, both shall point to
elements of the same array object, or one past the last
element of the array object; the result is the difference of
the subscripts of the two array elements. The size of the
result is implementation-defined, and its type (a signed
integer type) is ptrdiff_t defined in the <stddef.h> header.
If the result is not representable in an object of that
type, the behavior is undefined.
Huh? size_t and ptrdiff_t are both integral types, the first being
unsigned, and the second signed. The code above ensures that the
prtdiff_t value is not negative. I fail to see anything undefined
if we ignore the fact that strlen can only be defined in the
implementation.