There's a struct
struct Foo{
int a, b, c;
char* name;
};
with an initialization function
Foo_init(struct Foo* foo, const char* name){
// ... stuff
}
When I create a struct Foo object, I pass in a const char*, to serve as the object's name. Example:
struct Foo foo1;
Foo_init(&foo1, "foo1");
The goal is to "store" the content of "foo1" into foo1's char* variable.
I'm currently doing it like:
Foo_init(struct Foo* foo, const char* name){
foo->name = name;
// ... other stuff
}
but I wonder if the correct way is:
Foo_init(struct Foo* foo, const char* name){
int name_len = strlen(name) + 1;
foo->name = malloc(name_len);
memcpy(foo->name, name, name_len)
// ... other stuff
}
(I suppose either way is fine, since in this example the argument "foo1" is a string literal.)
- Which way is correct?
- What if the argument
const char* nameis no longer a string literal, but an arbitrary array with length determined at runtime? - What if the signature of
Foo_init()is notFoo_init(struct Foo* foo, const char* name)butFoo_init(struct Foo* foo, char* name)(ie. thechar*is no longerconst)? - More generally, when do I need to
malloc()/memcpy()memory for an incoming argument that is achar*(or anint*, or anything that owns a bunch of elements in memory), assuming I want "store it" inside astruct?
size_t-->size_t name_len = strlen(name) + 1;foo->name = name;should have warned about losingconst. Certainly this is not correct code.