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?
No, what you're trying to do is a shallow copy.
You probably want this:
BTW: I'm using
memcpyas there is no overlap between source and destination.Discalaimer: this is untested, unoptimized code and error checks are omitted for brevity.