sharptooth
sharptooth

Reputation: 170499

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 function 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?

Upvotes: 3

Views: 530

Answers (3)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215259

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;
}

Upvotes: 10

Nathan Fellman
Nathan Fellman

Reputation: 127428

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)

Upvotes: 3

pmg
pmg

Reputation: 108988

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;

Upvotes: 10

Related Questions