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.

3
  • Does DEBUG_PRINT_MEMLOC_EXIT check for allocation errors ? Commented Sep 22, 2010 at 2:53
  • yes,it does.I posted the macro expansion. Commented Sep 22, 2010 at 3:03
  • 1
    If malloc is crashing, then it probably means that you've written beyond the bounds of a block allocated with malloc() at some earlier point. Use valgrind, if it's supported on your platform, to check for this. Commented Sep 22, 2010 at 4:09

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.