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



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

`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`

我尝试过瓦尔格林德女巫的输出:

==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;
}

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

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

代码中的几个问题

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

当然你有内存泄漏

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

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

有多种方法可以分配 2Dint矩阵:

  • 您可以分配一个数组的数组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指向loopsintcats数组数组。

这种方法只有在 C 的早期版本中才有可能,如果loops是一个常量表达式,就像在你的程序中一样,但这个限制在 C99 中被取消了。

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

#include <stdio.h>
#include <stdlib.h> 
#define cats 3
#define loops 30
int main() {
int (*a)[loops] = malloc(sizeof(*a) * loops);
if (a != NULL) {
for (i = 0; i < cats; i++) {
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");
}
free(a);
}
return 0;
}

最新更新