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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The object allocation isn’t entirely correct (you should cast toThe string allocation is correct, but maybe not exactly what you want.Foo*and not tomystruct).The
strdup()function actually callsmalloc()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 callfree()on the string when you’re disposing theFooobject.If
foo->nameis for read-only purposes, declarefoo->nameas aconst char *and just writefoo->name = "Foo";to initialize it.EDIT:
Also note that
strdup()might returnNULL, and you should check for it! If it is I would than justassert()on it, because out-of-memory errors are pretty unrecoverable. Don’t try to handle such kind of errors. This also counts for allocating theFooobject too.