Query regarding deep copy of pointers inside a structure to another structure

57 views Asked by At

I have a query regarding the deep copy in C.

I can't share the real code but my code looks something like this:

struct a {
  char *t1; 
  char *t2; 
  int a; 
  int b; 
};

I have a s1 of type struct a whose values are dynamically assigned. I have another struct s2 to which I want to copy the contents of struct a . Since I have pointers, I need to do deep copy, so that i won't lose the values when I free(struct s1).

For doing deep copy, to beFin with, I have dynamically allocated struct s2 like below:

struct s2 = malloc(sizeof(struct a));

and now in another function, I am using memmove to copy the contents of s1 to s2:

memmove(s1.t1, &s2.t1, length_of_t1)

Is this the correct way of doing the deep copy?

1

There are 1 answers

7
Jabberwocky On

No, what you're trying to do is a shallow copy.

You probably want this:

struct a {
  char *t1; 
  char *t2; 
  int a; 
  int b; 
};
...
// assuming s1 points to a valid struct a
// and s1->t1 and s1->t2 point to valid C strings,
// the following lines perform a deep copy of s1 into s2

struct *s2 = malloc(sizeof(struct a));  // allocate new struct

memcpy(s2, s1, sizeof(struct a));       // copy the struct
// *s1 = *s1;                           // you also can use this instead of memcpy

s2->t1 = malloc(strlen(s1->t1) + 1);    // allocate space for t1
strcpy(s2->t1, s1->t1);                 // copy the bytes

s2->t2 = malloc(strlen(s1->t2) + 1);    // allocate space for t2
strcpy(s2->t2, s1->t2);                 // copy the bytes

BTW: I'm using memcpy as there is no overlap between source and destination.

Discalaimer: this is untested, unoptimized code and error checks are omitted for brevity.