0

I want to write a method in C that gives me a multidimensional array of uint16_t.

I write this:

uint16_t ** GRAPHICS_CreateImage(int width, int height)
{
  int x;
  uint16_t **image = (uint16_t **)malloc(width * sizeof(uint16_t *));

  for(x=0; x < width; x++)
  {
      GUI_DUMY(x * 5, 0, 0x00F0);
      uint16_t *xx = (uint16_t *)malloc(height * sizeof(uint16_t));
      if(xx == NULL)
      {
        GUI_DUMY(0, 30, 0x0000);
      }
      GUI_DUMY(x * 5, 10, 0x000F);
      image[x] = xx;
      GUI_DUMY(x * 5, 20, 0xF000);
  }
  GUI_DUMY(0, 100, 0x0000);

  return image;
}

The program runs on an LCD-Display (I cannot debug code) and I need to do GUI_DUMY to see squares on the screen. So... my problem is that the malloc in the for hangs when x == 55. (I run the method with width 480 and height 320.)

When I have not enough memory, the malloc has to be finished and xx has to be NULL.

But xx is never NULL.

I have read, this problem can arise because of buffer overflow when mallocing, but I don't know if that is my problem?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
10110010
  • 31
  • 3
  • 1
    Problem is certainly in other code. Post an [mcve]. Why check `xx ==NULL`, but not check `image == NULL`? – chux - Reinstate Monica Dec 30 '19 at 00:03
  • Also, you [don't need to, and shouldn't, cast the result of `malloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – kopecs Dec 30 '19 at 00:14
  • That's not a "multidimensional array". `image` is a pointer to an array of pointers to individual, separate one-dimensional arrays if `uint16_t` values. – Andrew Henle Dec 30 '19 at 10:47
  • I can not post an minimal example because the Code runs on an LCD-Module. – 10110010 Dec 30 '19 at 13:28

1 Answers1

0

I am not sure what GUI_DUMY does nor how you intend to use the image array returned by this function, but here are some ideas to investigate:

  • you allocate an array of width pointers to arrays of height 16-bit words. You might need to swap these quantities.
  • you allocate an array of pointers to arrays, but the caller might expect an actual 2D array, ie an array of arrays, which is a very different type of object.
chqrlie
  • 131,814
  • 10
  • 121
  • 189