strlen not checking for NULL

后端 未结 6 1243
小蘑菇
小蘑菇 2020-12-01 07:52

Why is strlen() not checking for NULL?

if I do strlen(NULL), the program segmentation faults.

Trying to understand the rationale be

6条回答
  •  情书的邮戳
    2020-12-01 08:26

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

提交回复
热议问题