Struct with pointers in C: solved exercise
Struct with pointers in C: solved exercise
If you searched for a solved struct with pointers in C, here is the critical difference between a shallow copy (with = or memcpy) and a deep copy, and why shallow-copying a struct with pointer members is a common source of bugs.
When a struct contains a char * or any pointer, a shallow copy duplicates the pointer but not the pointed-to data: both structs point to the same memory, and freeing one invalidates the other.
Problem statement
Define an Employee struct with fields name (dynamic pointer), age, and salary. Implement:
employee_create(name, age, salary): dynamically allocates the struct and duplicates the string.employee_copy(src): deep copy — new struct and new string.employee_free(e): frees the string and then the struct.
Demonstrate that modifying the copy does not affect the original.
C solution
Expected output
(Pointer addresses will differ between original and copy, proving they are independent.)
Common mistakes
- Copying the struct with
copy = *origormemcpy: duplicates thenamepointer, not the string. Both structs point to the same string; freeing one invalidates the other’s pointer. - Freeing
ebefore freeinge->name: thenameaddress is lost with the struct, causing a memory leak. - Using
strcpywithout allocating memory for the destination:strcpyassumes the destination already has enough space; without a priormallocthe memory is corrupted. - Not checking the return value of
mallocfor the string: if it fails after the struct was already allocated, the struct must be freed before returningNULL.
Practical use
This pattern is essential in any C module managing data with dynamic strings or buffers: in-memory database records, message queues, caching systems, and any structure that must be copied or serialized to pass to another function or thread.
Recommended next exercise
- qsort with structs in C: solved exercise
- List of structs in C: solved exercise
- Files in C: solved exercises
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
When is a shallow copy acceptable for structs with pointers?
Only when the copy’s lifetime does not exceed the original’s and you can guarantee that the original will not be freed while the copy is in use. In practice this guarantee is hard to maintain; deep copy is the safer default rule.
Is there an equivalent of clone or a copy constructor in C?
Not natively. The usual pattern is to manually implement an type_copy(const Type *src) function that performs the deep copy, following the same convention as employee_copy in this exercise.
What happens if the same memory is freed twice (double free)?
It is undefined behavior. In practice it usually corrupts the allocator’s internal heap structures, which can cause segmentation faults, infinite loops, or security vulnerabilities. To detect it, tools like Valgrind or AddressSanitizer (gcc -fsanitize=address) are indispensable.