For starters the function should be declared like
FrameNode * createframe( const char name[], const char path[], int duration );
because neither name
nor path
is changed in the function.
You did not allocate memory for list->name
, list->path
and frame
.
And moreover instead of frame
of the type FrameNode *
the function returns list
of the type Frame *
.
The named constant STR_LEN
does not make great sense when a character array is allocated dynamically as in your case with data members name
and path
of the structure Frame
.
You should at first allocate dynamically memory for an object of the type FrameNode
.
Then you should allocate memory for an object of the type Frame
and its data members name
and path
.
Thus the function definition can look the following way.
FrameNode * createframe( const char name[], const char path[], int duration )
{
FrameNode *frame = malloc( sizeof( FrameNode ) );
if ( frame != NULL )
{
char *name_data = NULL;
char *path_data = NULL;
size_t n = strlen( name );
name_data = malloc( n + 1 );
if ( name_data != NULL ) strcpy( name_data, name );
if ( name_data != NULL )
{
n = strlen( path );
path_data = malloc( n + 1 );
if ( path_data != NULL ) strcpy( path_data, path );
}
Frame *list = NULL;
if ( name_data != NULL && path_data != NULL )
{
list = malloc( sizeof( Frame ) );
if ( list != NULL )
{
list->name = name_data;
list->duration = duration;
list->path = path_data;
}
}
if ( list == NULL )
{
free( name_data );
free( path_data );
free( frame );
}
else
{
frame->frame = list;
frame->next = NULL;
}
}
return frame;
}
If you indeed need to restrict the length of the dynamically allocated strings then these statements
size_t n = strlen( name );
name_data = malloc( n + 1 );
if ( name_data != NULL ) strcpy( name_data, name );
and
n = strlen( path );
path_data = malloc( n + 1 );
if ( path_data != NULL ) strcpy( path_data, path );
should be replaced with
name_data = malloc( STR_LEN );
if ( name_data != NULL )
{
strncpy( name_data, name, STR_LEN );
name_data[STR_LEN - 1] = '\0';
}
and
path_data = malloc( STR_LEN );
if ( path_data != NULL )
{
strncpy( path_data, path, STR_LEN );
path_data[STR_LEN - 1] = '\0';
}
Otherwise there will be an inconsistence relative to stored data: some nodes will store strings while other will contain non-strings.