有没有一个标准的C函数可以计算字符串长度并限制长度上限?

3
考虑一种情况:我有一个已知长度的缓冲区,它可能存储了一个以null结尾的字符串,我需要知道字符串的长度。
问题在于,如果我使用strlen()函数并且该字符串最终不是以null结尾,则程序会在读取超出缓冲区结尾时遇到未定义行为。因此,我想要一个类似以下函数的函数:
 size_t strlenUpTo( char* buffer, size_t limit )
 {
     size_t count = 0;
     while( count < limit && *buffer != 0 ) {
        count++;
        buffer++;
     }
     return count;
 }

需要一个函数返回字符串的长度,但不要试图读取缓冲区末尾之外的内容。

C库中是否已经有这样的函数,还是我必须使用自己的函数?

3个回答

10

使用memchr(string, 0, limit),如下所示:

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

10

根据我的文档,POSIX拥有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;

请注意,如果您的系统没有 strnlen 函数,您可以使用我的答案作为替代品。将替代函数命名为 strnlen 并确保其与 POSIX 的 strnlen 函数具有相同的语义,这可能比创建一个不同命名且可能行为不同的版本更好。 - R.. GitHub STOP HELPING ICE

3
你可以使用 strnlen 函数。下面是它的手册页:
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)

1
注意CONFORMING TO 部分。它已经过时了;POSIX 2008规范化了这个函数。但当然它仍不是纯C。 - R.. GitHub STOP HELPING ICE

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接