noobatrilla noobatrilla - 1 year ago 54
C Question

How do I copy a 2d array into a temporary 2d array and return it?

I'm trying to copy a 2-d array of ints to a temporary 2-d array of ints and return it. I've had a go at it below, but I get a pretty suspicious malloc error. I tried inspecting it with valgrind, but couldn't find anything useful

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-settling error message is as follows:

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.

Answer Source

Your approach is correct, except for the size length in the inner loop: it should length * sizeof(int) or sizeof(**grid):

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

The cause for the unsettling error is the subarrays are allocated too small and you probably modify them in some other part of the program, causing some corruption of the malloc internal data that is detected at some later call to one of the allocation functions: malloc(), free(), calloc(), realloc()...

Note also that you do not check the return values of these malloc() calls. If for some reason malloc cannot allocate the memory, you will invoke undefined behavior instead of returning NULL gracefully.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download