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?
source
share