分配和释放二维数组 [英] alloc and free of 2d array

查看:51
本文介绍了分配和释放二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了2d array(matrix)+ alloc和free函数来管理内存,但是它不能很好地工作,valgrind打印很多错误和内存丢失的信息.

I made 2d array(matrix) + alloc and free functions to manage memory but it isnt working well, valgrind prints many errors and information that memory was lost.

Alloc:参数s表示矩阵的大小

Alloc: parametr s means size of matrix

int** alloc(int s)
{
    int** matrix;
    int i;

    matrix = (int**)malloc(s * sizeof(int*));
    for (i = 0; i < s; i++)
    {
        matrix[i] = calloc(s, sizeof(int));
    }

    return matrix;
}

免费

void matrix_free(int*** matrix, int s)
{
    int i;
    for(i = 0; i < s; i++)
    {
        free(*((matrix)+i));
    }
    free(matrix);

}

Valgrind:像这样的许多错误:

Valgrind: Many errors like this:

Invalid read of size 8
==3767==    at 0x4FAA8D4: buffer_free (in /lib/x86_64-linux-gnu/libc-2.24.so)
==3767==    by 0x4FAA942: __libc_freeres (in /lib/x86_64-linux-gnu/libc-2.24.so)
==3767==    by 0x4A276EC: _vgnU_freeres (in /usr/lib/valgrind/vgpreload_core-amd64-linux.so)
==3767==    by 0x4E73292: __run_exit_handlers (exit.c:98)
==3767==    by 0x4E73339: exit (exit.c:105)
==3767==    by 0x4E593F7: (below main) (libc-start.c:325)
==3767==  Address 0x52000e8 is 168 bytes inside a block of size 552 free'd
==3767==    at 0x4C2DD6B: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3767==    by 0x108BBB: matrix_free (m1.c:68)
==3767==    by 0x108B69: main (m1.c:58)
==3767==  Block was alloc'd at
==3767==    at 0x4C2CB3F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3767==    by 0x4EA7F2C: __fopen_internal (iofopen.c:69)
==3767==    by 0x108919: main (m1.c:16)
==3767== 
==3767== 
==3767== HEAP SUMMARY:
==3767==     in use at exit: 36 bytes in 3 blocks
==3767==   total heap usage: 7 allocs, 6 frees, 5,732 bytes allocated
==3767== 
==3767== LEAK SUMMARY:
==3767==    definitely lost: 36 bytes in 3 blocks
==3767==    indirectly lost: 0 bytes in 0 blocks
==3767==      possibly lost: 0 bytes in 0 blocks
==3767==    still reachable: 0 bytes in 0 blocks
==3767==         suppressed: 0 bytes in 0 blocks

推荐答案

在这种情况下,free函数不使用指向已分配内存的指针,而是指向该指针的指针.

The free function in this case doesn't take a pointer that points to the allocated memory, but a pointer to that pointer.

要释放内存,您需要首先获取该指针.

To free the memory you need to first obtain that pointer.

void matrix_free(int*** matrix, int s)
{
    int** m = *matrix;
    int i;
    for(i = 0; i < s; i++)
    {
        free( m[i] );
    }
    free( m );

    *matrix = NULL;
}

此变体还使您可以将参数设置为NULL:

This variant also enables you to set the argument to NULL:

matrix_free( &matrix , s );
assert( matrix == NULL );

这篇关于分配和释放二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆