Reputation: 13145
Is this the correct way to create a string in this case.
Foo* create()
{
Foo *foo = malloc(sizeof(Foo));
foo->name = strdup("Foo");
return foo;
}
I will later have to delete both foo and foo->name myself.
Upvotes: 1
Views: 84
Reputation: 1663
The object allocation isn't entirely correct (you should cast to The string allocation is correct, but maybe not exactly what you want.Foo*
and not to mystruct
).
The strdup()
function actually calls malloc()
for you, and you only need this construction if you want to modify the string at a later time (and don't increase its length!!!). You should not forget to call free()
on the string when you're disposing the Foo
object.
If foo->name
is for read-only purposes, declare foo->name
as a const char *
and just write foo->name = "Foo";
to initialize it.
EDIT:
Also note that strdup()
might return NULL
, and you should check for it! If it is I would than just assert()
on it, because out-of-memory errors are pretty unrecoverable. Don't try to handle such kind of errors. This also counts for allocating the Foo
object too.
Upvotes: 2
Reputation: 35069
It is correct, but you don't have to cast the return pointer of malloc
(and you shouldn't).
Upvotes: 0