strlen not checking for NULL

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

    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.

提交回复
热议问题