Home » Blog » Explain Deep Copy and Shallow Copy with examples?

Explain Deep Copy and Shallow Copy with examples?

In the following C program, struct variable st1 contains pointer to dynamically allocated memory. When we assign st1 to st2, str pointer of st2 also start pointing to same memory location. This kind of copying is called Shallow Copy.

# include <stdio.h> 
# include <string.h> 
# include <stdlib.h> 
  
struct test 
{ 
  char *str; 
}; 
  
int main() 
{ 
  struct test st1, st2; 
  st1.str = (char *)malloc(sizeof(char) * 20); 
  
  strcpy(st1.str, "GeeksforGeeks"); 
  
  st2 = st1; 
  st1.str[0] = 'X'; 
  st1.str[1] = 'Y'; 
  
  /* Since copy was shallow, both strings are same */
  printf("st1's str = %s\n", st1.str);  
  printf("st2's str = %s\n", st2.str); 
  
  return 0; 
}
  • OutPut
st1's str = XYeksforGeeks
st2's str = XYeksforGeeks

To do Deep Copy, we allocate new memory for dynamically allocated members and explicitly copy them.

# include <stdio.h> 
# include <string.h> 
# include <stdlib.h> 
  
struct test 
{ 
  char *str; 
}; 
  
int main() 
{ 
  struct test st1, st2; 
  st1.str = (char *)malloc(sizeof(char) * 20); 
  
  strcpy(st1.str, "GeeksforGeeks"); 
  
  st2 = st1; 
  
  // We add extra statements to do deep copy 
  st2.str = (char *)malloc(sizeof(char) * 20); 
  strcpy(st2.str, st1.str); 
  
  st1.str[0] = 'X'; 
  st1.str[1] = 'Y'; 
  
  /* Since copy was deep, both strings are different */
  printf("st1's str = %s\n", st1.str);  
  printf("st2's str = %s\n", st2.str); 
  
  return 0; 
}
  • OutPut
st1's str = XYeksforGeeks
st2's str = GeeksforGeeks

 

Leave a Reply

Your email address will not be published.