Does strlen() in C take the NULL pointer into account?
- User
Does strlen() in C take the NULL pointer into account?
Assistant
The
strlen()function in C does not count the null terminator ('\0') in its return value - it returns the number of characters before the null terminator.For example:
char str[] = "Hello"; size_t len = strlen(str); // Returns 5, not 6However, if you meant passing a NULL pointer to
strlen(), that's undefined behavior and will likely cause a segmentation fault:char *ptr = NULL; size_t len = strlen(ptr); // Undefined behavior - crash!If you need to safely handle NULL pointers, you should check before calling
strlen():char *ptr = get_string_somehow(); size_t len = 0; if (ptr != NULL) { len = strlen(ptr); }The function simply counts characters starting from the given address until it finds a
'\0', so it expects a valid pointer to a null-terminated string.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.