时谨慎使用免费()来释放malloc()函数使用的内存? [英] when to carefully use free() to free up malloc() used memory?

查看:126
本文介绍了时谨慎使用免费()来释放malloc()函数使用的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我许多问题,在这里SO阅读关于C的释放未使用的变量的内存free()函数的一些其他物品。就我而言,我有以下code座。

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;
}

以上的功能,我使用一个数组注入一个字符串块。我使用的malloc 以创建一个新的的char * 。在上述情况下,我需要做的免费(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.

推荐答案

STRC 是这个函数的返回值,所以你不叫免费(STRC)函数本身内部。你需要释放它的功能外,当此字符串不再被使用的时间。

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.

这篇关于时谨慎使用免费()来释放malloc()函数使用的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆