Need strnlen().

VLD/VMB gwyn at BRL.ARPA
Mon Nov 11 15:52:30 AEST 1985


Re: proposed strnlen()

All the str*() functions work with NUL-terminated strings.
Probably the best thing that could happen if you fed them
something else would be for the implementation to access
unallocated memory.  At least then you would be able to
find the bug.

Your suggestion would make more sense for the mem*()
functions, which work with arbitary byte arrays.  A good
generalization would be "find the first occurrence of a
given byte, not going beyond a certain distance".  If you
look up memchr(), you will see that that's what it does.

It is possible that your system is not System V compatible,
in which case the memchr() function may not be in your C
library.  But it is very easy to implement and there is no
need to invent a different-shaped wheel.
	char *memchr( const char *s, int c, int n );
returns a pointer to the first occurrence of `c' in the
first `n' bytes of memory area (whose lowest address is)
`s', or NULL if not found.  Calling this function with
`c' set to '\0' is equivalent to your proposed strnlen().
(You would have to handle the exception case, and use
whatever memchr() returns minus `s' in the regular case
for the length of the string.)



More information about the Comp.lang.c mailing list