简体   繁体   English

C 2D数组内存分配

[英]C 2D array Memory allocation

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(). 有时,代码在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: 但是,您应该检查乘法不会溢出,并且您的malloc()行可以用一种更简洁的方式编写:

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. 你什么也没退。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM