Junior — Middle
How is the length of a string calculated in GNU implementation using the strlen function?
sobes.tech AI
Answer from AI
In GNU implementation, the strlen function counts the length of a string by iterating through the characters of a char array until it encounters a null character \0, which signifies the end of the string in C style.
Working principle:
- The function takes a pointer to the start of the string.
- It iterates over the characters, incrementing a counter.
- It stops when it encounters the
\0character. - It returns the number of characters before
\0.
An example of a simplified implementation in C:
size_t strlen(const char *str) {
const char *s = str;
while (*s) {
s++;
}
return s - str;
}
In GNU libc, more complex techniques may be used for optimization, such as reading by words instead of bytes to speed up the search for the null byte, but the basic principle remains the same — searching for the first null character in memory.