ProgrammingBackend C Developer

Describe the features of working with structure assignment in the C language. How are structures copied, what are the advantages and limitations, what errors can occur?

Pass interviews with Hintsage AI assistant

Answer

C supports direct assignment of one structure to another of the same type: all fields are copied byte by byte (memcpy). This is convenient for quickly cloning a structure, for example:

struct Point { int x, y; }; struct Point p1 = {10, 20}; struct Point p2; p2 = p1; // Now p2.x=10, p2.y=20

Features:

  • All fields are copied "as is" (bit by bit).
  • If fields are pointers/arrays, only the pointer value is copied, not the content at that address (deep copy does not occur!).
  • Assignment works only for structures of the same type.

Trick question

"What happens if the structure contains a pointer to dynamically allocated memory, and you assign one structure to another?"

Many believe that all contents will be copied, but this is not the case.

Answer: Only the value of the pointer (the address) will be copied, not the data at that address. Both structure instances will point to the same memory.

struct Data { int *arr; }; struct Data d1; d1.arr = malloc(10 * sizeof(int)); struct Data d2 = d1; // d2.arr == d1.arr

Changing d2.arr will also change the memory visible to d1.arr.

Examples of real errors due to ignorance of the subtleties of the topic


Story 1

Data serialization: assigned a structure with an inner pointer buffer (malloc) — after copying, two different objects pointed to the same memory, and freeing both called free(). Result — double free and service crash.


Story 2

In an attempt to clone a complex structure, I forgot to make a deep copy of pointer fields. After modifying the copy, independence was expected, but the original was changed (and vice versa), losing data consistency.


Story 3

Stored a structure with a nested pointer to a string. Assigned the structure, after which one of the strings was freed, and the second structure suddenly "broke" (dangling pointer), causing the program to behave unpredictably.