正在处理一些处理矩阵的C代码。我已经创建了一个矩阵结构,使其更容易快速有效地创建它的许多实例,但我不知道为什么我的代码泄漏内存。目前我有以下代码:
typedef struct
{
size_t rows;
size_t cols;
double ** value;
}
*Matrix;
Matrix matCreate( size_t rows, size_t cols )
{
if(rows<=0 || cols<=0)
{
return NULL;
}
Matrix mat = (Matrix) malloc(sizeof(Matrix));
mat->rows = rows;
mat->cols = cols;
mat->value = (double **) malloc(rows*sizeof(double*));
for (int i=0; i< rows;i++)
{
mat->value[i] = (double *) malloc(cols * sizeof(double));
for( int j=0; j< cols;j++)
{
mat->value[i][j] = 0;
if(rows == cols && i==j )
{
mat->value[i][j] = 1;
}
}
}
return mat;
}
和我得到以下内存泄漏后运行valgrind。当运行代码时,它编译完全没有错误,仍然输出正确的输出。
==23609== Invalid write of size 8
==23609== at 0x400800: matCreate
==23609== by 0x4010E2: main
==23609== Address 0x5203048 is 0 bytes after a block of size 8 alloc'd
==23609== at 0x4C2DB8F: malloc
==23609== by 0x4007E8: matCreate
==23609== by 0x4010E2: main
==23609==
==23609== Invalid write of size 8
==23609== at 0x40081B: matCreate
==23609== by 0x4010E2: main
==23609== Address 0x5203050 is 8 bytes after a block of size 8 alloc'd
==23609== at 0x4C2DB8F:
==23609== by 0x4007E8: matCreate
==23609== by 0x4010E2: main
==23609==
==23609== Invalid read of size 8
==23609== at 0x40082F: matCreate
==23609== by 0x4010E2: main
==23609== Address 0x5203050 is 8 bytes after a block of size 8 alloc'd
==23609== at 0x4C2DB8F: malloc
==23609== by 0x4007E8: matCreate
==23609== by 0x4010E2: main
Matrix mat = (Matrix) malloc(sizeof(Matrix));
不好。它没有分配足够的内存。因此,您的程序具有未定义的行为。
size(Memory)
计算指针的大小,而不是struct
的大小。
必须是:
Matrix mat = malloc(sizeof(*mat));
定义真正是指针的Matrix
不是良好的编码实践。这会导致混乱。我建议将其定义为:
typedef struct
{
size_t rows;
size_t cols;
double ** value;
} Matrix;
,然后使用:
Matrix* matCreate( size_t rows, size_t cols ) { ... }
...
Matrix* mat = malloc(sizeof(*mat));
参见是否强制转换malloc的结果?