我正在尝试将二维整数数组复制到临时二维整数数组并返回它。我在下面进行了尝试,但是我遇到了一个非常可疑的 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;
}
Un-setting报错信息如下:
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
最佳答案
你的方法是正确的,除了内循环中的大小 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()
、重新分配()
...
另请注意,您不检查这些 malloc()
调用的返回值。如果由于某种原因 malloc
无法分配内存,您将调用未定义的行为,而不是优雅地返回 NULL
。
关于c - 如何将二维数组复制到临时二维数组中并返回它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39079699/