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.
We'll cover the following...
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.
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 ...