Search code examples
cunions

memcpy a void pointer to a union


Code:

union foo
{
    char c;
    int i;
};

void func(void * src)
{
    union foo dest;
    memcpy(&dest, src, sizeof(union foo));   //here
}

If I call func() like this:

int main()
{
    char c;
    int i;
    func(&c);
    func(&i);
    return 0;
}

In the call func(&c), the size of c is less than sizeof(union foo), which may be dangerous, right?

Is the line with memcpy correct? And if not, how to fix it?

What I want is a safe call to memcpy that copy a void * pointer to a union.


A little background: this is extracted from a very complicated function, and the signature of func() including the void * parameter is out of my control. Of course the example does nothing useful, that's because I removed all the code that isn't relevant to provide an example with minimum code.


Solution

  • Is the line with memcpy correct? And if not, how to fix it?

    you should pass the size of memory pointed by void pointer so you can know src has this much size so you just need to copy this much of data...

    Further more to be safe you should calculate the size of destination and based on that you should pass size so illegal access in reading and writing both can be avoided.