C 2D阵列内存分配

时间:2010-09-22 02:42:46

标签: c memory-management malloc

问候所有, 以下逻辑中是否存在分配2D数组的问题:

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;



}

宏扩展是:

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

有时代码在malloc()期间崩溃。

提前感谢。

2 个答案:

答案 0 :(得分:1)

没有任何根本性的错误 - 这种方法完全是苛刻的。但是,您应该检查乘法不会溢出,并且可以更清晰地编写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);

答案 1 :(得分:0)

我很惊讶它不会一直崩溃。你没有退货。