strlen innards
-
Can someone explain to me in layman's terms how this function works? https://codebrowser.dev/glibc/glibc/string/strlen.c.html Thank you.
-
Can someone explain to me in layman's terms how this function works? https://codebrowser.dev/glibc/glibc/string/strlen.c.html Thank you.
It counts the initial characters in the string until the pointer is aligned on a longword boundary. It then uses some clever bit manipulations to count the rest of the characters four at a time. If you run that code in the debugger you will be able to see exactly what happens.
-
Can someone explain to me in layman's terms how this function works? https://codebrowser.dev/glibc/glibc/string/strlen.c.html Thank you.
Presumably already clear what the 4/8 block is used in the first place. Googling with following provides some answers.
explain strlen himagic lomagic
Following line is the key
if (((longword - lomagic) & ~longword & himagic) != 0)
I tried eye balling that and using examples in my head but still not clear. I believe it is relying on arithmetic overflow. If I wanted to understand that I would write up some test code with examples characters (4 blocks) with zero at the end (position 4, 3, 2, 1). Then have it print the results of each clause in the above if using binary representation (1 and 0) to see how the bits look for each different example and for each part of the clause. Perhaps as a learning experience also copy that code into your own space and then write a test jig to time results via that and using the more straightforward (just by char) code. You should start with a large number of runs like probably at least 100,000.