Ad space (banner)
๐Ÿ”งC Lessons
Lesson 40 / 68

Shallow Copy vs. Deep Copy

This lesson covers the difference between a shallow copy and a deep copy in C, so you can avoid bugs caused by unintended data sharing. It's for anyone searching "C shallow copy deep copy."

Assigning a C struct directly copies it by value, but if the struct contains a pointer, the data the pointer points to isn't duplicated along with it. This is the state called a "shallow copy."

The example's Person struct has a pointer field, Address *address. Copy this struct directly, and both the copy and the original still point at the same Address โ€” changing one affects the other.

A common early mistake is the bug of "I thought I made a copy, but the original data changed too." This happens especially often when handling a struct that contains a pointer.

In real projects, implementing a "deep copy" โ€” newly allocating and copying the data a pointer points to as well โ€” is what's needed to prevent unintended data sharing.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)