Is strlen on a string with uninitialized values undefined behavior?

后端 未结 4 1887
暖寄归人
暖寄归人 2020-12-19 06:23

strlen returns the number of characters that precede the terminating null character. An implementation of strlen might look like this:



        
4条回答
  •  隐瞒了意图╮
    2020-12-19 07:05

    The behavior of the variant that you are showing is well defined under these circumstances.

    • The bytes of the uninitialized array have all indeterminate values, with exception of the 10th element that you set to 0.
    • Accessing an indeterminate value would only be UB if the address of the underlying object would be never taken or if the value is a trap for the corresponding type.
    • Since this is an array and access to array elements is through pointer arithmetic, the first case is not relevant, here.
    • Any char value can be accessed without UB, the clauses about trap representations in the standard explicitly exclude all character types from that.
    • Thus the values that you are dealing with are simply "unspecified".
    • Reading unspecified values may according to some members of the C standards committee give different results each time, what some call a "whobly" state or so. This property is not relevant, here, since your function reads any such value at most once.
    • So your access to the array elements gives you any arbitrary but valid char value.
    • You are sure that your for loop stops at latest at position 9, so you will not overrun your array.

    So no "bad" things beyond the visible may happen if you use your specific version of the function. But having a function call that produces unspecified results is certainly nothing you want to see in real code. Something like this here leads to very subtle bugs, and you should avoid it by all means.

提交回复
热议问题