Is there a standard C function for calculating the string length to a certain limit?

Consider the situation: I have a buffer of known length that supposedly stores a string with a terminating zero, and I need to know the length of the string.

The problem is what I use strlen(), and the line is not a null termination when the program runs in undefined behavior when reading outside the end of the buffer. Therefore, I would like to have a function like:

 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 outside the end of the buffer.

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

+3
source share
3 answers

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;
+10

you can use strnlen. This is it 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)
+3
source

Source: https://habr.com/ru/post/1780187/


All Articles