开发者

Is there a standard C function for computing the string length up to some limit?

Consider a situation: I have a buffer of known length that presumably stores a null-terminated string and I need to know the length of the string.

The problem is if I use strlen() and the string turns out to be not null-terminated the program runs into undefined behavior while reading beyond the buffer end. So I'd like to have a functio开发者_如何转开发n like the following:

 size_t strlenUpTo( char* buffer, size_t limit )
 {
     size_t count = 0;
     while( count < limit && *buffer != 0 ) {
        count++;
        buffer++;
     }
     return count;
 }

so that it returns the length of the string but never tries to read beyond the buffer end.

Is there such function already in C library or do I have to use my own?


Use memchr(string, 0, limit), as in:

size_t strlenUpTo(char *s, size_t n)
{
    char *z = memchr(s, 0, n);
    return z ? z-s : n;
}


According to my documentation, POSIX has size_t strnlen(const char *src, size_t maxlen);

n = strnlen("foobar", 7); // n = 6;
n = strnlen("foobar", 6); // n = 6;
n = strnlen("foobar", 5); // n = 5;


you can use strnlen. This is it's manpage:

NAME
       strnlen - determine the length of a fixed-size string

SYNOPSIS
       #include <string.h>

       size_t strnlen(const char *s, size_t maxlen);

DESCRIPTION
       The  strnlen  function returns the number of characters in
       the string pointed to by s, not including the  terminating
       '\0' character, but at most maxlen. In doing this, strnlen
       looks only at the first maxlen characters at s  and  never
       beyond s+maxlen.

RETURN VALUE
       The  strnlen  function  returns strlen(s), if that is less
       than maxlen, or maxlen if there is no '\0' character among
       the first maxlen characters pointed to by s.

CONFORMING TO
       This function is a GNU extension.

SEE ALSO
       strlen(3)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜