Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove cross-type uses of memcpy. #152

Closed
briansmith opened this issue Mar 14, 2016 · 2 comments
Closed

Remove cross-type uses of memcpy. #152

briansmith opened this issue Mar 14, 2016 · 2 comments

Comments

@briansmith
Copy link
Owner

Some version of the C standard says:

If a value is copied into an object having no declared type using memcpy or memmove, or is copied as an array of character type, then the effective type of the modified object for that access and for subsequent accesses that do not modify the value is the effective type of the object from which the value is copied, if it has one.

I read "or is copied as an array of character type," to be modifying "using memcpy or memmove" and not modifying "having no declared type".

In many cases, we use memcpy to transfer the contents of something of a buffer of an unstructured type (e.g. a byte array) into a structured value (e.g. a struct or a uint32_t). From the above, it is only (guaranteed to be) valid to do this when the destination has a declared type. In practice, that means that we can only safely use this pattern when the destination is a local variable.

@briansmith
Copy link
Owner Author

briansmith commented Dec 12, 2016

Here's a good way to make it easy to verify the code is correct in this respect: For every use of memcpy copying a value to another value of the same type T, create a wrapper function:

static inline void t_copy(T *dest, const T *src) { memcpy(dest, src, sizeof(T)); }

or, if we're copying arrays:

static inline void t_copy_array(T *dest, const T *src, size_t n) {
    /* TODO: how to prevent |sizeof(T) * n| from overflowing? */
    memcpy(dest, src, sizeof(T) * n);
}

When this is done, every use of memcpy should be in one of these functions.

@briansmith
Copy link
Owner Author

Actually, I'm closing this in favor of #201, since the pattern I suggest above can likely be used to solve the more general problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant