前几天遇到一个有意思的问题,实现strlen 不考虑线程安全:
下面是我的实现:
1 size_t strlen(const char* s) 2 { 3 const char* p = s; 4 while (*p++); 5 return p-1-s; 6 }
Glibc 2.19 的实现:
针对此实现,函数头部分没太明白, size_t strlen (str) const char *str; 详细情况参见Glibc 2.19, 下面的实现还是比较经典的兼顾性能和体系机构。
1 /* Return the length of the null-terminated string STR. Scan for 2 the null terminator quickly by testing four bytes at a time. */ 3 size_t 4 strlen (str) 5 const char *str; 6 { 7 const char *char_ptr; 8 const unsigned long int *longword_ptr; 9 unsigned long int longword, himagic, lomagic; 10 11 /* Handle the first few characters by reading one character at a time. 12 Do this until CHAR_PTR is aligned on a longword boundary. */ 13 for (char_ptr = str; ((unsigned long int) char_ptr 14 & (sizeof (longword) - 1)) != 0; 15 ++char_ptr) 16 if (*char_ptr == '