Why is strlen()
not checking for NULL?
if I do strlen(NULL)
, the program segmentation faults.
Trying to understand the rationale behind it (if any).
strlen(s) returns the length of null-terminated string s. The length does not count the null character.
What is strlen() strlen() is a function to find the length of a string. It counts total characters which are presented in a string, eliminating the null character. The total number of characters in string includes, alphabets, special characters, and numbers, with blank spaces.
An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .
Ok, I need to add some explanation. My application is getting a string from a shared memory (which is of some length), therefore it could be represented as an array of characters. If there is a bug in the library writing this string, then the string would not be zero terminated, and the strlen could fail.
The rational behind it is simple -- how can you check the length of something that does not exist?
Also, unlike "managed languages" there is no expectations the run time system will handle invalid data or data structures correctly. (This type of issue is exactly why more "modern" languages are more popular for non-computation or less performant requiring applications).
A standard template in c would look like this
int someStrLen; if (someStr != NULL) // or if (someStr) someStrLen = strlen(someStr); else { // handle error. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With