csegmentation-faultstrlen

strlen not checking for NULL


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).


Solution

  • 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.
     }