C 中的清理函数

Gid*_*pta 1 c malloc free

我有一个 C 程序,它分配了一些需要在程序退出执行之前清除的缓冲区。我的main程序看起来像这样

int main(int argc, char** argv){
    // Some code
    // ...
    // ...
    void* data1 = malloc(someSize);
    void* data2 = malloc(someSize);
    double* result = malloc(resultSize);
    double* buffer = malloc(buffSize);
    // Some code
    // ...
    // First exit point
    if(someExitcondition){
        // free all allocated memory
        exit(1);
    }
    // Some code
    // ...
    // Second exit point
    if(someOtherExitcondition){
        // free all allocated memory
        exit(1);
    }
    // Some code
    // ...

    // free all allocated memory
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我想通过调用一个cleanUp()函数来使清理更容易,该函数将free分配在堆中的所有内存。我想在每次exit(1)调用之前和return 0行之前调用这个函数(基本上用// free all allocated memory调用替换每个注释cleanUp())。我的问题是,我怎么传指针data1data2resultbuffercleanUp()使得它们能够被释放?

这就是我想要做的。这是正确的方法吗?

void cleanUp(void* p1, void* p2, void* p3, void* p4){
    // call to free for each pointer
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ons 5

如果您曾经被教导永远不要使用goto,那么 like 就是一个很好的使用时机的典型例子goto

int main(int argc, char** argv){
    int ret_status = 0;
    // Some code
    // ...
    // ...
    void* data1 = malloc(someSize);
    void* data2 = malloc(someSize);
    double* result = malloc(resultSize);
    double* buffer = malloc(buffSize);
    // allocation failure: first exit point
    if(!(data1 && data2 && result && buffer)){
        ret_status = 1;
        goto cleanup;
    }
    // Some code
    // ...
    // Second exit point
    if(someOtherExitcondition){
        ret_status = 1;
        goto cleanup;
    }
    // Some code
    // ...

cleanup:
    // free all allocated memory     
    free(data1);
    free(data2);
    free(result);
    free(buffer);

    return ret_status;
}
Run Code Online (Sandbox Code Playgroud)

如果与给定的示例不同,您还exit()从嵌套函数调用,请查看atexit()Jonathan Leffler 的回答中给出的using 。

  • 这是我推荐的方法。 (2认同)