I'm trying to create an instance of a struct with a const member.
Because the member is const, I'm creating a temporary value that has it initialized explicitly.
#include <string.h>
#include <stdlib.h>
typedef struct Thing {
const char *value;
} Thing;
void createThing(const char *value) {
// Create a temporary instance of Thing to initialize the const value
Thing temporary = {
.value = value
};
// Create a new thing
Thing *thing = (Thing *)malloc(sizeof(Thing));
if(thing == NULL)
return NULL;
// Copy the contents of temporary into the result
memcpy(thing, &temporary, sizeof(Thing));
// Return the result
return thing;
}
Is it safe to use value
this way, or should I create a new copy? For example:
const char *valueCopy = (char *)malloc(sizeof(char) * (strlen(value) + 1));
strcpy(valueCopy, value);
My reasoning is that the argument value
will fall out of scope after the function call ends, and without copying, the value in the struct will become invalid.
As a side-note, I think I'm doing the right thing by copying from a temporary struct, but glad to be told otherwise.