[英]Invalid write/read of size 8
Working on some C code working with Matrices. 处理一些使用矩阵的C代码。 I have created a Matrix struct to make it easier to create many instances of it quickly and efficiently but I am not sure why my code is leaking memory.
我创建了一个Matrix结构,以使其更容易快速,高效地创建它的许多实例,但是我不确定为什么我的代码会泄漏内存。 Currently I have the following code:
目前,我有以下代码:
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;
}
And I am getting the following memory leaks after running valgrind. 运行valgrind后,我收到以下内存泄漏。 When running the code it compiles completely without error and still outputs the right output.
运行代码时,它可以完全编译而不会出错,并且仍然可以输出正确的输出。
==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
The line 线
Matrix mat = (Matrix) malloc(sizeof(Matrix));
is not good. 不好 It does not allocate enough memory.
它没有分配足够的内存。 As a consequence, your program has undefined behavior.
因此,您的程序具有未定义的行为。
size(Memory)
evaluates to the size of a pointer, not the size of the struct
. size(Memory)
计算的是指针的大小,而不是struct
的大小。
It needs to be: 它必须是:
Matrix mat = malloc(sizeof(*mat));
Defining Matrix
that is really a pointer is not good coding practice. 定义确实是指针的
Matrix
并不是良好的编码习惯。 It will lead to confusion. 这会导致混乱。 I suggest defining it as:
我建议将其定义为:
typedef struct
{
size_t rows;
size_t cols;
double ** value;
} Matrix;
and then use: 然后使用:
Matrix* matCreate( size_t rows, size_t cols ) { ... }
...
Matrix* mat = malloc(sizeof(*mat));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.