strlen not checking for NULL

2019-01-14 06:25发布

Why is strlen() not checking for NULL?

if I do strlen(NULL), it seg faults.

Trying to understand the rationale behind it (if any).

标签: c strlen
6条回答
\"骚年 ilove
2楼-- · 2019-01-14 06:46

The standard does not require it, so implementations just avoid a test and potentially an expensive jump.

查看更多
【Aperson】
3楼-- · 2019-01-14 06:55

Three significant reasons:

  • The standard library and the C language are designed assuming that the programmer knows what he is doing, so a null pointer isn't treated as an edge case, but rather as a programmer's mistake that results in undefined behaviour;

  • It incurs runtime overhead - calling strlen thousands of times and always doing str != NULL is not reasonable unless the programmer is treated as a sissy;

  • It adds up to the code size - it could only be a few instructions, but if you adopt this principle and do it everywhere it can inflate your code significantly.

查看更多
姐就是有狂的资本
4楼-- · 2019-01-14 07:00

The portion of the language standard that defines the string handling library states that, unless specified otherwise for the specific function, any pointer arguments must have valid values.

The philosphy behind the design of the C standard library is that the programmer is ultimately in the best position to know whether a run-time check really needs to be performed. Back in the days when your total system memory was measured in kilobytes, the overhead of performing an unnecessary runtime check could be pretty painful. So the C standard library doesn't bother doing any of those checks; it assumes that the programmer has already done it if it's really necessary. If you know you will never pass a bad pointer value to strlen (such as, you're passing in a string literal, or a locally allocated array), then there's no need to clutter up the resulting binary with an unnecessary check against NULL.

查看更多
SAY GOODBYE
5楼-- · 2019-01-14 07:04

A little macro to help your grief:

#define strlens(s) (s==NULL?0:strlen(s))
查看更多
在下西门庆
6楼-- · 2019-01-14 07:04
size_t strlen ( const char * str );

http://www.cplusplus.com/reference/clibrary/cstring/strlen/

Strlen takes a pointer to a character array as a parameter, null is not a valid argument to this function.

查看更多
看我几分像从前
7楼-- · 2019-01-14 07:05

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.
 }
查看更多
登录 后发表回答