开发者

C 2D array Memory allocation

开发者 https://www.devze.com 2023-01-17 14:57 出处:网络
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)

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 fai开发者_JS百科led (%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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消