如何将2d数组复制到临时2d数组并返回?

时间:2016-08-22 12:34:04

标签: c memory-management memory-leaks valgrind memcpy

我试图将2-d的int数组复制到临时的2-d数组并返回它。我已经在下面进行了操作,但我得到了一个非常可疑的malloc错误。我尝试用valgrind检查它,但找不到任何有用的东西

int **get_grid_state(int **grid, int height, int length) {
    int **grid_state;
    int i;

    grid_state = malloc(height * sizeof(int*));

    for (i = 0; i < height; i++) {
        grid_state[i] = malloc(length);
        memcpy(grid_state[i], grid[i], length);
    }
    return grid_state;
}

取消解决错误消息如下:

program: malloc.c:2372: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.
Aborted

1 个答案:

答案 0 :(得分:2)

您的方法是正确的,除了内循环中的length大小:它应该length * sizeof(int)sizeof(**grid)

        grid_state[i] = malloc(length * sizeof(**grid));
        memcpy(grid_state[i], grid[i], length * sizeof(**grid));

unsettling 错误的原因是子阵列分配得太小而你可能在程序的其他部分修改它们,导致malloc内部数据的某些损坏稍后调用其中一个分配函数时检测到:malloc()free()calloc()realloc() ......

另请注意,您不会检查这些malloc()来电的返回值。如果由于某种原因malloc无法分配内存,您将调用未定义的行为,而不是优雅地返回NULL