You need to free the val
field, because strdup
generates a new copy of the string which is dynamically allocated.
To avoid many heap allocations, if you have an upper bound to the string length, then there is no need to use strdup
. Just declare a static char array inside the struct itself:
const size_t MAX_LENGTH = 32;
typedef struct TestStruct
{
char val[MAX_LENGTH];
..
}
and use strncpy
to copy the content.
In addition there's no need to cast malloc returned pointer to the specified type, as in C a void*
is convertible to other types without the need of an explicit downcast (this is not true in C++).