我正在编写一个代码,其中有几个函数。在每个函数中,都有几个应动态分配内存的变量。这些函数被重复调用,因此,分配一次内存并在 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/