0

我正在使用 c 代码编写一个 matlab mex 函数。我在释放分配的内存时遇到了一些麻烦。我在使用以下代码时遇到问题。如果我去掉所有的 free() 行,代码可以工作,但我有内存泄漏。这意味着代码在我内存不足之前只能运行几次。所有调用的函数都有指针作为输入,所以我从不改变函数中指针的地址。我在内存分配/释放过程中犯了错误吗?

void RLS_(int *M, int *N, double *h, double *y, double *P, double *theta)
{

int i;
double *Ph;//[*M];
double hPh;
double inv;
double *inv1;
double *invPh;//[*M];
double *hTtheta;//[*N];
double *ymhTtheta;//[*N];
double **ADD;//[*M][*N];
double **invPhhT;//[*M][*M];
double **SUB;//[*M][*M];

Ph = (double *) malloc (*M * sizeof(double));
if (Ph == NULL)
    return;

invPh = (double *) malloc (*M * sizeof(double));
if ( invPh == NULL)
    return;

hTtheta = (double *) malloc (*N * sizeof(double));
if (hTtheta == NULL)
    return;

ymhTtheta = (double *) malloc (*N * sizeof(double));
if (ymhTtheta == NULL)
    return;

ADD = (double **) malloc (*M * sizeof(double *));
if (ADD == NULL)
    return;
for (i=0;i<*M;i++)
{
    ADD[i] = (double *) malloc(*N *sizeof(double));
    if (ADD[i] == NULL)
        return;
}
invPhhT = (double **) malloc (*M * sizeof(double *));
if (invPhhT == NULL)
    return;
for (i=0;i<*M;i++)
{
    invPhhT[i] = (double *) malloc(*M *sizeof(double));
    if (invPhhT[i] == NULL)
        return;
}
SUB = (double **) malloc (*M * sizeof(double *));
if (SUB == NULL)
    return;
for (i=0;i<*M;i++)
{
    SUB[i] = (double *) malloc(*M *sizeof(double));   
    if (SUB[i] == NULL)
        return;
}


matvectmult_(M,M,P,h,Ph);                  

hPh = vectordot_(M,h,Ph);                   

inv = 1/(1+hPh); inv1 =&inv;

scalarmult_(M,inv1,Ph,invPh);               

vectmatmult_(M,N,theta,h,hTtheta);          

vectorsub_(N,y,hTtheta,ymhTtheta);          

vectvectmult_(M,N,invPh,ymhTtheta,*ADD);    

vectvectmult_(M,M,invPh,h,*invPhhT);     

matmulc_(M,M,M,*invPhhT,P,*SUB);           

// Update theta
matrixadd_(M,N,theta,*ADD,theta);

// Update P
matrixsub_(M,M,P,*SUB,P);               

free(Ph);
free(invPh);
free(hTtheta);
free(ymhTtheta);
for (i=0;i<*M;i++)
    free(ADD[i]);
free(ADD);
for (i=0;i<*M;i++)
    free(invPhhT[i]);
free(invPhhT);
for (i=0;i<*M;i++)
    free(SUB[i]);
free(SUB);
}
4

2 回答 2

0

这里有一点——你有很多很多的 return 语句,并且在任何这些调用之前你都不会释放任何内存。例如,如果 invPh 为 NULL,则分配给 Ph 的内存将不会被释放。

于 2013-06-13T01:14:55.720 回答
0

考虑到@Owen 所说的,我会将您的malloc语句放在一个只执行一次的 do-while 循环中,然后将您的所有return语句break替换为。

do {
    // mxMalloc
    if (someVar[i] == NULL)
        break;

    // etc...
    // The real meat of your code inside the do-while loop
} while 0 == 1;
// mxFree functions out here

我对 mex 函数的编码有点生疏。这样做可能有更好的做法,但这可能会有所帮助。

您可能还需要检查您尝试释放的每个变量是否也是!= NULL如此,尽管该free函数可能会自动执行此操作。

编辑:更改了上面的代码。我认为@horchler 在评论中说得最好:你应该使用mxMallocandmxFree而不是mallocand free

于 2013-06-13T03:36:42.477 回答