views:

94

answers:

2

Greetings all, Is there any issue in the following logic for allocating 2D array:

unsigned char **
Malloc2D_uchr(int ht, int wt, unsigned char initv)
{
    int h, w;
    unsigned char **x;

    x = (unsigned char **) malloc(sizeof(void *) * ht);
    DEBUG_PRINT_MEMLOC_EXIT(x,"malloc failed (%s,%i)\n",sizeof(void *)*ht);

    x[0] = (unsigned char *) malloc(sizeof(unsigned char) * ht * wt);
    DEBUG_PRINT_MEMLOC_EXIT(x[0],"malloc failed (%s,%i)\n",sizeof(unsigned char)*ht*wt);

    for (h = 1; h < ht; h++)
    {
        x[h] = x[h - 1] + wt; /* + is a pointer summation */
    }
    for (h = 0; h < ht; h++)
    {
        for (w = 0; w < wt; w++)
        {
            x[h][w] = initv;
        }
    }

    return x;



}

The macro expansion is :

#define DEBUG_PRINT_MEMLOC_EXIT(t,s,z);     if(t == NULL){\
                                                printf(s,__FILE__,__LINE__,z);\
                                                printf("Malloc size = %d\n",z);\
                                                exit(-1);\
                                    }

Sometimes the code crash during malloc().

thanks in advance.

A: 

I'm surprised it doesn't crash all the time. You don't return anything.

Marcelo Cantos
Im sorry,it returns the pointer 'x' . I edited the post
umanga
+1  A: 

There's nothing fundamentally wrong - that approach is perfectly cromulent. However, you should check that the multiplications don't overflow, and your malloc() lines can be written in a cleaner way:

if ((ht > SIZE_MAX / sizeof x[0]) || (wt > (SIZE_MAX / sizeof x[0][0]) / ht))
    /* error, too large */

x = malloc(sizeof x[0] * ht);
x[0] = malloc(sizeof x[0][0] * ht * wt);
caf