Home  >  Article  >  Backend Development  >  When Does an Object Created with memcpy in C Begin Its Lifetime?

When Does an Object Created with memcpy in C Begin Its Lifetime?

DDD
DDDOriginal
2024-11-08 18:55:02140browse

When Does an Object Created with memcpy in C   Begin Its Lifetime?

Uncertain Object Creation with memcpy in C

In C , when an object is allocated, its buffer of bytes is copied from its source. However, the exact mechanism of this copying is unspecified, raising questions about the object's lifetime.

Consider the following code snippet:

#include <cstdlib>
#include <cstring>

struct T   // trivially copyable type
{
    int x, y;
};

int main()
{
    void *buf = std::malloc( sizeof(T) );
    if ( !buf ) return 0;

    T a{};
    std::memcpy(buf, &amp;a, sizeof a);
    T *b = static_cast<T *>(buf);

    b->x = b->y;

    free(buf);
}

In this code, a buffer is allocated using malloc. A trivial copyable object a is then copied into this buffer using memcpy. A reference to the copied object is stored in b.

The question is: When does the lifetime of the object pointed to by b begin? Namely, when it is copied using memcpy or when it is pointed to by b?

Unclear Standard

The C standard is currently silent on this issue. A paper entitled "Object Lifetime, Low-level Programming, and memcpy" proposes that uses of memcpy for trivially copyable types be recognized as object construction, but it has not yet been discussed or incorporated into the standard.

Draft Standard Interpretation

The C 14 draft standard suggests that an object is created when it is defined, created using a new-expression, or created by the implementation when necessary. However, the cases covered in the standard for copying trivially copyable types seem to refer only to already existing objects.

Proposal for Implicit Object Creation

Proposal p0593 attempts to address this issue by defining implicit object creation operations, including malloc and memcpy. This proposal has not yet been reviewed.

Conclusion

Currently, the C standard does not specify when an object created using memcpy begins its lifetime. Therefore, the behavior of the code snippet provided is undefined. Proposal p0593 offers a potential solution to this ambiguity, but it has yet to be accepted into the standard.

The above is the detailed content of When Does an Object Created with memcpy in C Begin Its Lifetime?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn