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

后端 未结 3 1190
野性不改
野性不改 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:44

    Example 2 is invalid. The analysis in your question is correct.

    Example 1 is valid. A structure type never holds a trap representation, even if one of its members does. This means that structure assignment, on a system where trap representations would cause problems, must be implemented as a bytewise copy, rather than a member-by-member copy.

    6.2.6 Representations of types

    6.2.6.1 General

    6 [...] The value of a structure or union object is never a t rap representation, even though the value of a member of the structure or union object may be a trap representation.

    0 讨论(0)
  • 2020-12-02 15:53

    C++ discussion

    Short answer: In C++, there is no such thing as accessing "reading" a class instance; you can only "read" non-class object, and this is done by a lvalue-to-rvalue conversion.

    Detailed answer:

    typedef struct { int *p; } T;
    

    T designates an unnamed class. For the sake of the discussion let's name this class T:

    struct T {
        int *p; 
    };
    

    Because you did not declare a copy constructor, the compiler implicitly declares one, so the class definition reads:

    struct T {
        int *p; 
        T (const T&);
    };
    

    So we have:

    T a;
    T b = a;    // Access through a non-character type?
    

    Yes, indeed; this is initialization by copy constructor, so the copy constructor definition will be generated by the compiler; the definition is equivalent with

    inline T::T (const T& rhs) 
        : p(rhs.p) {
    }
    

    So you are accessing the value as a pointer, not a bunch of bytes.

    If the pointer value is invalid (not initialized, freed), the behavior is not defined.

    0 讨论(0)
  • 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) {
        /* ... */
    }
    
    0 讨论(0)
提交回复
热议问题