如何在二维数组中正确分配空间,同时避免内存损坏?

时间:2019-04-07 09:32:30

标签: c memory-leaks malloc

对于算法,我想在每次需要时将空间分配给二维数组,相反,我得到了这个错误

`main.run: malloc.c:2406: sysmalloc: Assertion `(old_top ==   initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted`

我已经尝试了Valgrind女巫的输出:

==2903== Memcheck, a memory error detector
==2903== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==2903== Using Valgrind-3.12.0.SVN and LibVEX; rerun with -h for copyright info
==2903== Command: ./main.run
==2903== 
==2903== Invalid write of size 4
==2903==    at 0x1087B7: main (main.c:18)
==2903==  Address 0x51d70e4 is 0 bytes after a block of size 4 alloc'd
==2903==    at 0x4C2BBAF: malloc (vg_replace_malloc.c:299)
==2903==    by 0x108787: main (main.c:17)
==2903== 

valgrind: m_mallocfree.c:303 (get_bszB_as_is): Assertion 'bszB_lo == bszB_hi' failed.
valgrind: Heap block lo/hi size mismatch: lo = 12, hi = 368578837618884608.
This is probably caused by your program erroneously writing past the
end of a heap block and corrupting heap metadata.  If you fix any
invalid writes reported by Memcheck, this assertion failure will
probably go away.  Please try that before reporting this as a bug.


host stacktrace:
==2903==    at 0x38083828: show_sched_status_wrk (m_libcassert.c:343)
==2903==    by 0x38083944: report_and_quit (m_libcassert.c:419)
==2903==    by 0x38083AD1: vgPlain_assert_fail (m_libcassert.c:485)
==2903==    by 0x38091882: get_bszB_as_is (m_mallocfree.c:301)
==2903==    by 0x38091882: get_bszB (m_mallocfree.c:311)
==2903==    by 0x38091882: vgPlain_arena_malloc (m_mallocfree.c:1734)
==2903==    by 0x3804FAD4: vgMemCheck_new_block (mc_malloc_wrappers.c:350)
==2903==    by 0x3804FCA6: vgMemCheck_malloc (mc_malloc_wrappers.c:385)
==2903==    by 0x380D7B53: do_client_request (scheduler.c:1866)
==2903==    by 0x380D7B53: vgPlain_scheduler (scheduler.c:1425)
==2903==    by 0x380E6416: thread_wrapper (syswrap-linux.c:103)
==2903==    by 0x380E6416: run_a_thread_NORETURN (syswrap-linux.c:156)

sched status:
  running_tid=1

Thread 1: status = VgTs_Runnable (lwpid 2903)
==2903==    at 0x4C2BBAF: malloc (vg_replace_malloc.c:299)
==2903==    by 0x108787: main (main.c:17)

这是导致问题的代码:

#include <stdio.h>
#include <stdlib.h> 

#define cats 3
#define loops 30

int main() {
    int **a;
    int i,j;

    a = (int **)malloc(sizeof(int *));

    for (i = 0; i < cats; i++)
        for (j = 0; j < loops; j++) {
            a[i] = (int *)malloc(sizeof(int));
            a[i][j] = i + j;
        }

    for (i = 0; i < cats; i++) {
        for (j = 0; j < loops; j++)
            printf("%d ", a[i][j]);
        printf("\n");
    }

    return 0;
}

错误是如何引起的,如何避免?

这种类型的内存分配是不好的做法吗?

3 个答案:

答案 0 :(得分:1)

您的代码中有几个问题

a = (int **)malloc(sizeof(int *));

必须

a = (int **)malloc(sizeof(int *)*cats); /* size for cats pointers rather than just 1 */

for (i=0; i<cats; i++)
   for (j=0; j<loops; j++) {
       a[i] = (int *)malloc(sizeof(int));
       a[i][j] = i+j;
   }

必须

for (i=0; i<cats; i++) { /* '{' added */
    a[i] = (int *)malloc(sizeof(int) * loops); /* moved and loops int rather than 1 */
    for (j=0; j<loops; j++) {
        a[i][j] = i+j;
    }
} /* '}' added */

使用这些修复程序,可以在 valgrind 下进行编译和执行:

pi@raspberrypi:/tmp $ gcc -g -pedantic -Wextra -Wall c.c
pi@raspberrypi:/tmp $ valgrind ./a.out
==5795== Memcheck, a memory error detector
==5795== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==5795== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==5795== Command: ./a.out
==5795== 
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 
==5795== 
==5795== HEAP SUMMARY:
==5795==     in use at exit: 372 bytes in 4 blocks
==5795==   total heap usage: 5 allocs, 1 frees, 1,396 bytes allocated
==5795== 
==5795== LEAK SUMMARY:
==5795==    definitely lost: 12 bytes in 1 blocks
==5795==    indirectly lost: 360 bytes in 3 blocks
==5795==      possibly lost: 0 bytes in 0 blocks
==5795==    still reachable: 0 bytes in 0 blocks
==5795==         suppressed: 0 bytes in 0 blocks
==5795== Rerun with --leak-check=full to see details of leaked memory
==5795== 
==5795== For counts of detected and suppressed errors, rerun with: -v
==5795== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
p

当然你有内存泄漏

答案 1 :(得分:0)

a = (int **)malloc(sizeof(int *));动态为一个指针分配空间并返回指向它的指针。对于任何i> 0,您都无法访问a[i],因为它将超出范围。要为多个指针分配空间,您需要将适当的大小传递给malloc

要么...

a = malloc(sizeof*a * cats);

...或...

a = malloc(sizeof (int*[cats]));

...会的。另外,由于所有范围都相等,因此可以省去锯齿状数组,并将整个对象分配在一个块中:

int (*a)[loops] = malloc(sizeof (int[cats][loops]));

更少的分配意味着出错的机会更少。

答案 2 :(得分:-1)

分配2D int矩阵有多种方法:

  • 您可以分配int的数组。

  • 您可以将指针数组分配给int的数组,并为每个指针分配不同的int数组。这是您尝试过的方法,但是分配大小不正确。

指向int 数组的指针的数组的大小应为cats * sizeof(int *)。并且int的每个数组都应该在外部循环中以loops * sizeof(int)的大小分配,而不是在内部循环中分配。

此外,您应该在退出程序之前释放这些对象,以便Valgrind可以看到干净的盘子。

这是更正的版本:

#include <stdio.h>
#include <stdlib.h> 

#define cats 3
#define loops 30

int main() {
    int **a;
    int i, j;

    a = malloc(cats * sizeof(int *));

    for (i = 0; i < cats; i++) {
        a[i] = malloc(loops * sizeof(int));
        for (j = 0; j < loops; j++) {
            a[i][j] = i + j;
        }
    }

    for (i = 0; i < cats; i++) {
        for (j = 0; j < loops; j++)
            printf("%d ", a[i][j]);
        printf("\n");
    }

    for (i = 0; i < cats; i++)
        free(a[i]);
    free(a);

    return 0;
}

这种类型的间接2D矩阵通常不受欢迎,原因是:

  • 分配更为复杂且速度较慢,尤其是如果您要避免由于部分分配失败而导致的内存泄漏,在此不做。
  • 通常访问效率较低,因为编译器会生成2次内存读取来读取一个值,而不是可能的乘法和一次读取。
  • 解除分配更加复杂。

有一些优点,这里不需要这些优点:

  • 可能不分配一些行
  • 可以共享相同的行(以复杂的重新分配为代价)
  • 行的大小可以不同,但​​是不再是矩阵了
  • 线路可以有效交换。

另一种方法,被认为是唯一的真正的 2D矩阵,它对矩阵指针使用单一分配和不太明显的类型:

    int (*a)[loops] = malloc(sizeof(int) * loops * cats);

可以这样写:

    int (*a)[loops] = malloc(sizeof(*a) * cats);

或更可能更可读:

    int (*a)[loops] = malloc(sizeof(int[cats][loops]));

a指向cats loops的{​​{1}}个数组。

仅当int是常量表达式(如您程序中的常量表达式)时,这种方法才可能在C的早期版本中使用,但是在C99中取消了此限制。

以下是使用此方法的程序的简化版本:

loops