Programming Tips - C/C++: A simple and fast strlen() implementation

Date: 2009may26 Date: 2026oct1 Language: C/C++ Q. C/C++: A simple and fast strlen() implementation A. From OpenBSD source:
size_t strlen(const char *str) { const char *s; for (s = str; *s; ++s) ; return (s - str); }
This is just for information. You should use the library function. glibc's is faster but its crazy complicated http://www.google.com/search?q=glibc+strlen Example Full Use:
#include <stdio.h> // Renamed the function to avoid conflict size_t bsd_strlen(const char *str) { const char *s; for (s = str; *s; ++s) ; return (s - str); } int main() { { // Test with a short string const char *str = "12345"; printf("length of '%s' is %d\n", str, bsd_strlen(str)); } { // Test with empty string const char *str = ""; printf("length of <empty> is %d\n", bsd_strlen(str)); } { // Test with NULL const char *str = NULL; printf("length of <null> is %d\n", bsd_strlen(str)); } }
Output:
length of '12345' is 5 length of <empty> is 0 Segmentation fault (core dumped) ./tst