内存泄漏
void zero_out_data(matrix *res, int rows, int cols)
matrix *res
malloc退出函数并传递给
zero_out_data
. 在里面
零输出数据
res
是自由的,马洛克又回来了。如果你想改变指针
物件
的值,则需要如下参数
matrix **res
.
如果您想要零输出数据,无需malloc新矩阵,只需malloc
data
make_matrix
函数可以将malloc内存用于
数据
.
void zero_out_data(matrix *res, int rows, int col) {
if (res->data == NULL) {
make_matrix(res, rows, cols);
} else if (res->rows != rows || res->cols != cols) {
if ((res->rows*res->cols) != (rows*cols))
{
free(res->data);
res->data = NULL;
make_matrix(res, rows, cols);
}
}
res->rows = rows;
res->cols = cols;
for (int i =0; i < (rows*cols); i++)
{
res->data[i] = 0.0;
}
}
sigmoid(matrix_add(matrix_dot(network->weights[k], activation), network->biases[k]));
?
你可以用
static
或全局变量来实现您想要的。这将不是线程安全和可重入的。示例如下:
matrix *matrix_dot(matrix *in_a, matrix *in_b)
{
static matrix res = {0, 0, NULL}; // static variable
// calculate the res's cols and rows number
zero_out_data(&res, res_cols, res_rows); // malloc new data
// do some math.
return &res;
}
// matrix_add will be just like matrix_dot
// I was wrong about sigmod no need new matrix. sigmod can also do it like matrix_dot.
可以使用全局变量替换静态变量。
matrix *matrix_dot(matrix *in_a, matrix *in_b, matrix *res)
{
zero_out_data(res, xxx, xxx);
// do some math
return res;
}
// matrix_add will be the same.
// define local variables.
matrix add_res, dot_res, sig_res;
add_res->data = NULL;
dot_res->data = NULL;
sig_res->data = NULL;
sigmod(matrix_add(matrix_dot(network->weights[k], activation, &dot_res), network->biases[k], &add_res), &sig_res)
// Now remember to free data in matrix
free(add_res->data);
free(dot_res->data);
free(sig_res->data);