gpt4 book ai didi

c - 将函数返回的指针作为输入传递给其他函数时如何避免内存泄漏?

转载 作者:行者123 更新时间:2023-12-01 13:42:20 25 4
gpt4 key购买 nike

我正在尝试编写一个简单的 C 矩阵库,它动态分配所需的内存并允许“嵌套”函数调用(如 fun1(fun2(x)))以避免执行长时间操作时声明过多的临时变量。但是,我无法摆脱因从未释放函数内部创建的结构而导致的内存泄漏。下面的例子清楚地表明了这一点。关于如何在不声明其他临时变量的情况下解决该问题的任何建议?

非常感谢

#include <stdio.h>
#include <stdlib.h>

struct _MatrixF{
uint8_t rows;
uint8_t cols;
float* mat;
};
typedef struct _MatrixF* Matrix;

Matrix newMatrix(uint8_t rows, uint8_t cols){
Matrix matrix = malloc(sizeof(struct _MatrixF));
matrix->rows = rows;
matrix->cols = cols;
matrix->mat = malloc(rows * cols * sizeof(float));
return matrix;
}

Matrix matIdentity(uint8_t rows, uint8_t cols){
Matrix matrix = newMatrix(rows, cols);
uint16_t ii;
for (ii = 0; ii < (cols * rows); ii++)
matrix->mat[ii] = (((ii / cols) == (ii % cols))? 1.0f : 0.0f);
return matrix;
}


Matrix matAdd(Matrix lhs, Matrix rhs){
Matrix m = newMatrix(lhs->rows, lhs->cols);
uint16_t ii;
for (ii = 0; ii < (lhs->cols * lhs->rows); ii++) {
m->mat[ii] = lhs->mat[ii] + rhs->mat[ii];
}
return m;
}

Matrix matMult(Matrix lhs, Matrix rhs){
uint8_t i, j, k;
Matrix result = newMatrix(lhs->rows, rhs->cols);
for (i=0; i < lhs->rows; i++)
for (j=0; j < rhs->cols; j++)
for (k=0; k < lhs->cols; k++)
MAT(result, i, j) += MAT(lhs, i, k) * MAT(rhs, k, j);
return result;
}

void mprint(Matrix m){
printf("%dx%d\n", m->rows, m->cols);
for(int i=0; i<m->rows; i++) {
for (int j = 0; j<m->cols; j++)
printf("%4.6f\t",(float) m->mat[(i) * m->cols + (j)]);
printf("\n");
}
}

int main(int argc, const char * argv[]) {
Matrix A = matIdentity(4, 3);
Matrix B = matIdentity(3, 2);
Matrix C = matIdentity(2, 4);
Matrix D = matIdentity(4, 4);
uint16_t len = 64000;
while (len--){
Matrix E = matAdd(D, matAdd(D, matMult(matMult(A, B),C)));
mprint(matMult(A, B));
mprint(A);
mprint(E);
}
return 0;
}

最佳答案

C 在自动处理这个问题上并没有提供多少帮助。您可以存储指向临时对象的指针,并在每次迭代结束时释放它们:

while (len--){
Matrix t1, t2, t3, t4;
Matrix E = matAdd(D, t1=matAdd(D, t2=matMult(t3=matMult(A, B),C)));
mprint(t4=matMult(A, B));
mprint(A);
mprint(E);
matFree(t1);
matFree(t2);
matFree(t3);
matFree(t4);
}

关于c - 将函数返回的指针作为输入传递给其他函数时如何避免内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38944763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com