Your function is legal and does nothing wrong. However, you should document it, indicating that the lines are not copied, only pointers.
So, if the transmitted data has a shorter lifespan than the structure itself, you may encounter undefined behavior. Example:
mystruct*func()
{
char a[]="foo";
char b[]="bar";
return mystruct_new(a,b);
}
mystruct*func2()
{
char *a="foo";
char *b="bar";
return mystruct_new(a,b);
}
int main()
{
mystruct *s = func();
printf(s->a);
mystruct *s2 = func2();
printf(s2->a);
mystruct *s3 = mystruct_new("foo","bar");
printf(s3->a);
}
- undefined , s->a
, ( func
).
, s2->a
, .
, :
mystruct* mystruct_new(const char* str1, const char* str2){
mystruct *s = malloc(sizeof(mystruct));
s->str1 = strdup(str1);
s->str2 = strdup(str2);
return s;
}
. free
, .