Yes free
, however, you could consider a different name that makes it clear it is allocating memory. Also, you could make use of sprintf
for combining 2 strings and strdup
for just copying one.
char* create_section_name(const char* section, const char* value) {
const int sectionLen = strlen(section);
if(sectionLen>0) {
//+1 for the period and +1 for the null
char *tmp = (char *)malloc((sectionLen + strlen(value) + 2) * sizeof(char));
//do that often? consider a newString(size) macro. See below
sprintf(tmp, "%s.%s", section, value);
return tmp;
}
else {
return strdup(value);
}
}
This assumes you don't need the full STR_LEN
, it uses just enough in both cases.
newString
macro I suggested:
#define newString(size) (malloc((size) * sizeof(char)))
Or it can even automatically add one for the null:
#define newString(size) (malloc(((size)+1) * sizeof(char)))
Then malloc is replaced with this:
char *tmp = newString(sectionLen + strlen(value) + 1); //+1 for period