views:

939

answers:

4

Hi,

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?

+4  A: 

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.

Timo Geusch
+5  A: 

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.

Greg Hewgill
+8  A: 

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;
paxdiablo
A: 

You are right, but please distinguish: you can make a deep copy, but you can not tell on how many bytes pointer points to.

doc
How can you make a deep copy? It is not known if the structure is homogeneous. It is not known if it is a linked list...
avp
I was to the nature of the question. "Is it possible to do a deep copy of structure which contains a void pointer?" - yes it is possible. Is it possible to tell how many data there is without additional field - no it isn't possible, at least if it's not some kind of special data like null char terminated char* or whatever.
doc