when to carefully use free() to free up malloc() used memory?

雨燕双飞 提交于 2019-11-27 06:15:40

问题


I read from many question here in SO and some other articles regarding free() function in c that frees the memory of unused variables. In my case, I have the following code block.

char *injectStrAt(char *str, char *strToIn, int pos)
{
    char *strC = malloc(strlen(str) + strlen(strToIn) + 1);
    strncpy(strC, str, pos);
    strC[pos] = '\0';
    strcat(strC, strToIn);
    strcat(strC, str + pos);
    return strC;
}

The above function I use to inject a string block in to an array. I am using malloc to create a new char*. In the above case do I need to do free(strC) ? advice pls.


回答1:


strC is the return value of this function, so you don't call free(strC) inside the function itself. You need to free it outside the function, the time when this string is not used anymore.




回答2:


Since your function is returning strC, one presumes it must remain valid after the return of this function, thus this function must not free() that buffer. Once it's freed, the buffer is no longer valid so must not be used.

Your caller is responsible for freeing it in this case.




回答3:


No you shouldn't free strC inside this function because it is the return value of this function. If you do so the statement:

return strC;

will return some unexpected or garbage value.

char* stringA = injectStrAt(str, strToIn, pos);
printf("StringA: %s"); // unexpected value.

So when should you free up the memory? Well, you should do it after the value of strC is returned from the function injectStrAt() to stringA, in this particular case. Although generally memory is freed when the string or the variable to which the memory was allocated is no longer required.

char* stringA = injectStrAt(str, strToIn, pos);
/... use the string

free(stringA);


来源:https://stackoverflow.com/questions/22298751/when-to-carefully-use-free-to-free-up-malloc-used-memory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!