Flexible array member not getting copied when I make a shallow copy of a struct

Solution 1:

Does anyone know what I am doing wrong?

Trying to use assignment to copy a struct with a flexible array member. From the standard (6.7.2.1):

The assignment *s1 = *s2 only copies the member n [i.e. the part of the struct that isn't a flexible array]; if any of the array elements are within the first sizeof (struct s) bytes of the structure, they might be copied or simply overwritten with indeterminate values.

Basically, when the C compiler sees a struct with a flexible array member, it doesn't know how big it really is, so it treats it as being big enough to hold the other members, plus possibly some more:

In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply.

That's what sizeof(*one) is, and that's the size of what gets copied when you do *oneCopy = *one;.

Since you do apparently know the size of the entire structure, in order to malloc it, just copy that many bytes using memcpy. Or if you're concerned that that's somehow unportable (honestly I'm not sure), do the assignment, then use a loop to copy each element from one->friends to
oneCopy->friends.