c - 释放 C 中 static 关键字定义的动态分配的内存

标签 c memory-management static

我正在编写一个代码,其中有几个函数。在每个函数中,都有几个应动态分配内存的变量。这些函数被重复调用,因此,分配一次内存并在 main 末尾释放它是合乎逻辑的。

main 函数如下所示:

//Some code here
while (err < tolerance){
        CalculateMismatch(M, err);
        //Update M and err and do other things
}
//Here is end of main, where I should free all the memories being allocated dynamically in other functions

此代码显示 CalculateMismatch 被调用了多次。所以,我只在这个函数中分配一次内存。像这样的事情:

function CalculateMismatch(Some arguments){
        //The following line is illegal in C, but I do not know how to allocate the memory just once and reuse it several times.
        static double *variable1 = malloc(lengthofVar1 * sizeof(variable1));
        //Rest of the code
}

我的问题是我不知道如何访问main中的CalculateMismatch中定义的变量。请让我知道应该如何释放变量,或者是否有更有效的方法来分配和释放内存。 感谢您提前提供的帮助。

提供有关我的代码的更多详细信息: 到目前为止,我已经全局定义了所有变量,并在 main 中动态分配了内存。但由于变量的数量很大,并且其中一些变量仅在一个特定函数中使用,因此我决定将定义移至函数内部。但是,我不知道如何释放每个函数内分配的内存。

最佳答案

这是不正确的:

 static double *variable1 = malloc(lengthofVar1 * sizeof(variable1));

你可能想要:

 static double *variable1 = malloc(lengthofVar1 * sizeof(*variable1));

不幸的是,您无法从函数外部释放此变量,除非您执行某些操作将其传回。

对此没有直接简单的解决方案。当然,一种解决方案是将变量移出一步:

static double *variable1 = 0;

function CalculateMismatch(Some arguments){

    if (!variable1) variable1 = malloc(lengthofVar1 * sizeof(*variable1));

        //Rest of the code
}

...
int main(...)
{
    ... 

    free(variable1);
}

关于c - 释放 C 中 static 关键字定义的动态分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15551985/

相关文章:

c - 尝试生成大型数据集时出现问题

c - 尝试从文件中读取数字,但不断收到段错误 :11. -C

c - 字节顺序是否也适用于位顺序?

c - mmap 返回无法分配内存,即使有足够的内存

c - 当在堆上请求大块内存时,如果 RAM 上没有连续空间,是否在磁盘上分配(交换)?

python - 静态变量的问题

c++ - 写回全局变量

c# - 当创建大量位图图像并将其保存为每像素图像一位时,物理内存使用异常

java - 静态方法中的android上下文未定义

go - 这段代码中/static/是什么意思?