C正确使用免费

Kei*_*ler 1 c memory free

我相信我这样做是对的,但我想确定一下.在一个程序中,我使用两个指针指向由函数返回的已分配内存.当我完成使用那个内存free()时,我会使用那些相同的指针来指向新分配的内存空间.这是我的程序,给出一个我的意思的例子(评论显示我的思考过程):

int main(void)
{
    char *data, *url;
        int i = 1;

    while(i)
    {
        printf("Enter URL: ");
        if(!(url = getstr())) return 1;                                  //url now points to allocated memory from getstr();
        if(strlen(url) <= 0) i = 0;
        if(data = readsocket(url, 80, "http")) printf("\n%s\n\n", data); //data now points to allocated memory from readsocket();
        else printf("\n\n");
        free(url);                                                       //free allocated memory that url points to url
        free(data);                                                      //free allocated memory that data points to data
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是正确的,还是有更好的更普遍的优先方法呢?或者我只是完全做错了?

jle*_*ahy 5

假设你的函数getstrreadsocketmalloc内存,那么这是完全正常的.

我唯一的建议是,在释放内存的同一范围内分配内存通常很有用,这通常有助于解决何时需要释放内容的问题.

例如:

url = malloc(URL_MAX_LEN);
if (!url) return 1;
if (!getstr(url)) {
    free(url);
    return 1;
}
/* do something with url */
free(url);
Run Code Online (Sandbox Code Playgroud)

如果您有很多对象和退出点,使用goto执行此操作会很不错.

object1 = malloc(OBJECT1_SIZE);
/* do work, if there's an error goto exit1 */
object2 = malloc(OBJECT2_SIZE);
/* do work, if there's an error goto exit2 */
object3 = malloc(OBJECT3_SIZE);
/* do work, if there's an error goto exit3 */
exit3:
free(object3);
exit2:
free(object2);
exit1:
free(object1);
return 1;
Run Code Online (Sandbox Code Playgroud)

如果你的对象变得更复杂并且需要大量的工作来创建和销毁,那么你可以将malloc和free包装起来,但是对于你的create/destroy函数应用完全相同的规则是至关重要的,就像malloc/free以避免泄漏一样.作为一个良好的实践,你应该总是有一个毁灭来匹配一个创建,即使它只是包装自由.以这种方式出错会更加困难.

struct x *create_x() {
    struct x *p = malloc(10);
    p->val1 = 7;
    return p;
}
void destroy_x(struct x *p) {
    free(p);
}
Run Code Online (Sandbox Code Playgroud)

  • 作为一般准则,我提出C的*三个规则*:`malloc`,`goto`和`free`应该总是在一起,或者根本不是. (2认同)