写入/读取大小无效8

时间:2016-11-11 23:21:54

标签: c valgrind

使用Matrices处理一些C代码。我已经创建了一个Matrix结构,以便更快速有效地创建它的许多实例,但我不确定为什么我的代码会泄漏内存。目前我有以下代码:

    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

1 个答案:

答案 0 :(得分:3)

该行

    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));

请参阅Do I cast the result of malloc?