Benny K
Benny K

Reputation: 2087

Code crashes in memcpy due to faulty pointer arithmetic

For some reason I can't understand the following code crashes (without any error message; gcc 7.4.0 Ubuntu 16.04, QT5) at the second memcpy in the loop so I am guessing that my pointer arithmetic is wrong but I don't understand why:

#include <stdio.h>
#include <string.h>

#define ROWS 48
#define COLS 48
#define CHANNELS 3
#define NUM_PIX ((ROWS) * (COLS) * (CHANNELS))
struct MyImage
{
  int width;
  int height;
  int channels;
  unsigned char rawData[NUM_PIX];
};

int main()
{
  const int numIm = 16;
  MyImage theClsImArr[numIm];
  unsigned char ImArr[numIm][ROWS][COLS][CHANNELS];
  int Bytes2Copy = NUM_PIX * sizeof(unsigned char);
  for (int i = 0; i < numIm; i++ )
     memcpy(theClsImArr[i].rawData,ImArr + i * NUM_PIX ,Bytes2Copy ); // works when i = 0, crashes at i = 1

  return 0;
}

Upvotes: 0

Views: 211

Answers (1)

Erlkoenig
Erlkoenig

Reputation: 2754

Use ImArr+i instead of ImArr + i * NUM_PIX. The addition will automatically factor in the size of the array element, which is equal to a whole image block.

Upvotes: 5

Related Questions