strlen not checking for NULL

后端 未结 6 1241
小蘑菇
小蘑菇 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

    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.

提交回复
热议问题