Search⌘ K
AI Features

Deep and Shallow Copy

Explore the concepts of deep and shallow copying of C structures, especially when they contain pointer members. Understand how to safely copy data using manual deep copies to avoid pointer sharing and memory errors.

Introduction

Copying structures is a common and useful operation. However, it can raise a subtle problem. What happens when structures contain pointer members or other resources (file descriptors, sockets, and so on)? To answer the question, we’ll consider the following example. We’ll model an employee structure, which may contain the following data:

  • Employee’s name
  • Employee’s ID
  • Employee’s salary

Starting code

Let’s transpose this scenario in code. We define the structure at lines 4–9. Inside main, we create two employees at lines 13–14. We then print the members of e1 and e2 to see if the code works fine.

C
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char name[32];
int id;
float salary;
} TEmployee;
int main()
{
TEmployee e1 = { "John", 1, 1500 };
TEmployee e2 = { "Jane", 2, 2000 };
printf("Employee: %s %d %f\n", e1.name, e1.id, e1.salary);
printf("Employee: %s %d %f\n", e2.name, e2.id, e2.salary);
return 0;
}

Output:

Employee: John 1 1500.000000
Employee: Jane 2 2000.000000

The output is correct and matches our expectations.

Copying structures

Let’s say we hire a new employee called John, for the same salary as the existing employee named John (1500). Since all the members, except the id, will be the same, we might as well just copy the structure of John instead of manually filling in a new one. We can use the assignment (=) operator to copy a structure. We are doing this in line 19 inside the code. After we copy the data, we have to change the id of e3 (line 20 ...