我正在使用 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);
}