Because it’s always easier to see code…
My parser fills this object:
typedef struct pair {
char* elementName;
char* elementValue;
} pair;
My interpreter wants to read that object and fill this one:
typedef struct thing {
char* label;
} thing;
Should I do this:
thing.label = pair.elementName;
or this:
thing.label = (char*)malloc(strlen(pair.elementName)+1);
strcpy(thing.label, pair.elementName);
EDIT: Yes, I guess I should have specified what the rest of the program will do with the objects. I will eventually need to save “pair” to a file. So when thing.label is modified, then (at some point) pair.elementName needs to be modified to match. So I guess the former is the best way to do it?
I would personally do the former, but it’s a tradeoff. The former avoids the need to allocate new memory and copy data to it, but the latter avoids the confusion of aliasing by keeping
thing.labelandpair.elementNamepointing to separate memory addresses, which means you need to free both of them (with the former you need to be sure to free exactly one, to avoid either a memory leak or a double free)