When is it valid to access a pointer to a “dead” object?

后端 未结 3 1253
野性不改
野性不改 2020-12-02 15:09

First, to clarify, I am not talking about dereferencing invalid pointers!

Consider the following two examples.

Example 1

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 15:57

    My interpretation is that while only non-character types can have trap representations, any type can have indeterminate value, and that accessing an object with indeterminate value in any way invokes undefined behavior. The most infamous example might be OpenSSL's invalid use of uninitialized objects as a random seed.

    So, the answer to your question would be: never.

    By the way, an interesting consequence of not just the pointed-to object but the pointer itself being indeterminate after free or realloc is that this idiom invokes undefined behavior:

    void *tmp = realloc(ptr, newsize);
    if (tmp != ptr) {
        /* ... */
    }
    

提交回复
热议问题