C: deep copying - structure with a void pointer
-
19-09-2019 - |
Question
I've got a following struct
struct teststruct
{
int *a;
void *data;
};
Is it possible to do a deep copy of structure which contains a void pointer? I assume that I cannot tell how many bytes data
pointer points to? So I cannot malloc specified number of bytes and do memcpy. Am I right?
Solution
No. Since you do not know the type that the void* points to, a deep copy is out of the question.
In addition, you could not even deep copy a
since it may point to either a single int
ot an array of them.
Typically in C, you would have a structure which carries the data types of it's contents if you wished to be able to do deep copies. For example:
struct teststruct {
int a_sz;
enum voidType vt;
int *a;
void *data;
};
Then you could use a_sz
to figure out how many integers the memory pointed to by a
was composed of and the enumerated type of data
, although technically it could also be an array so you may need a d_sz
as well.
Another trick is to have data
point to a structure that carries it's own data type embedded in it, such as:
typedef struct {
enum voidType vt;
union {
int i;
float f;
double d;
}
} tVoidType;
OTHER TIPS
If you have no information on the size of the data pointed to by void *data
I would say you cannot successfully deep copy this struct.
You are correct, you cannot tell how many bytes have been allocated for data
. In fact, you can't even be sure that data
points to malloc()
ed memory; it could be pointing to anything on the heap, stack, or global space.
Even if you could find out the size of the data, you still cannot know the structure of the internal data, which means that a proper "deep copy" would not be possible. A deep copy wouldn't stop at the first pointer depth.
You are right, but please distinguish: you can make a deep copy, but you can not tell on how many bytes pointer points to.