Search code examples
cstructmemcpy

Copy struct to an other


I want to copy some data stored in a struct to an other. Does the code below work?? Is it recommended or not?

#define SIZE 100
struct {
int *a;
int *b;
} Test;
Test t1;
t1.a = malloc(SIZE);
t1.b = malloc(SIZE);

Test t2;
memcpy(t2,t1,sizeof(Test));

Solution

  • Whether it works depends on what you intend it to do. It copies the bits from t1 to t2, including padding, but of course it copies the pointers, not the pointed-to values.

    If you don't care about the padding bits - and why should you - a simple assignment

    Test t2 = t1;
    

    is all you need to copy the pointers.

    If you want the pointed-to values duplicated and copied, neither your code nor simple assignment works.

    To copy the pointed-to memory blocks, first of all, you must know their size. There is no (portable) way to find out the size of the pointed-to memory block from the pointer.

    If the size is given by a #define, you can of course reuse that, otherwise you need to store the sizes of the allocated blocks somewhere.

    But since the newly allocated memory blocks have different addresses than the blocks to be copied, we need not copy the pointer vlaues from t1 to t2 at all.

    Test t2;
    t2.a = malloc(SIZE);  /* be aware that this is bytes, not number of ints */
    t2.b = malloc(SIZE);
    if (t2.a == NULL || t2.b == NULL) {
        /* malloc failed, exit, or clean up if possible */
        fprintf(stderr,"Allocation failure, exiting\n");
        exit(EXIT_FAILURE);
    }
    /* malloc was successful in both cases, copy memory */
    memcpy(t2.a, t1.a, SIZE);
    memcpy(t2.b, t1.b, SIZE);