I have the following function which gets called multiple times in my code:
char* get_section_name(const char* section, const char* value) {
char *tmp = (char *)malloc(STR_LEN * sizeof(char));
if(strlen(section)>0) {
strcat(tmp, section);
strcat(tmp,".");
}
strcat(tmp, value);
return tmp;
}
and I call it in other functions like this:
section_name = get_section_name(data->model_name,"params_default");
What is the best way to free this memory? Can I just call free(section_name) when I am done?
Yes
free, however, you could consider a different name that makes it clear it is allocating memory. Also, you could make use ofsprintffor combining 2 strings andstrdupfor just copying one.This assumes you don’t need the full
STR_LEN, it uses just enough in both cases.newStringmacro I suggested:Or it can even automatically add one for the null:
Then malloc is replaced with this: