Is storing an invalid pointer automatically undefined behavior?

前端 未结 7 1410
谎友^
谎友^ 2020-11-27 06:52

Obviously, dereferencing an invalid pointer causes undefined behavior. But what about simply storing an invalid memory address in a pointer variable?

Consi

7条回答
  •  抹茶落季
    2020-11-27 07:34

    Some architectures have dedicated registers for holding pointers. Putting the value of an unmapped address into such a register is allowed to crash. Integer overflow/underflow is allowed to crash. Because C aims to work on a broad variety of platforms, pointers provide a mechanism for safely programming unsafe circuits.

    If you know you won't be running on exotic hardware with such finicky characteristics, you don't need to worry about what is undefined by the language. It is well-defined by the platform.

    Of course, the example is poor style and there isn't a good reason to do it.

提交回复
热议问题