为矩阵赋值时的奇怪行为 (C/C++)

Strange behavior when assigning values to a matrix (C/C++)

我正在使用 malloc 和为它们分配向量 image 的一些值。 像往常一样,我使用两个整数 (i, j) 来为这项工作创建循环。第一次,当i=0和j=0时,它赋值如下:197给matR[0][0],211给matG[0][0],219给matB[0][0]。到现在为止还可以。这些是我想要的价值观。但这里出现了奇怪的行为:在某些点上,新值被分配给 matR[0][0]、matG[0][0]、matB[0][0]!

这是执行我所说的代码的一部分:

int i, j, k;
std::vector<unsigned char> image; //the raw pixels
unsigned error = lodepng::decode(image, width, height, filename);

matR = (unsigned char**)malloc(sizeof(unsigned char)*width);
matG = (unsigned char**)malloc(sizeof(unsigned char)*width);
matB = (unsigned char**)malloc(sizeof(unsigned char)*width);

k=0;
for(i=0; i<width; i++) {
  matR[i] = (unsigned char*)malloc(sizeof(unsigned char)*height);
  matG[i] = (unsigned char*)malloc(sizeof(unsigned char)*height);
  matB[i] = (unsigned char*)malloc(sizeof(unsigned char)*height);

  for(j=0; j<height; j++) {
    matR[i][j] = image[k++];
    matG[i][j] = image[k++];
    matB[i][j] = image[k++];
    k++; //separator
}

我添加了一些代码来调试代码,运行 在终端上,我得到了以下输出: http://imgur.com/XvQIGYk

*说明当i=100,j=0时,matR[0][0]的值改为176。

这是怎么回事?

这一行:

matR = (unsigned char**)malloc(sizeof(unsigned char)*width);

应该是:

matR = (unsigned char**)malloc(sizeof(unsigned char *)*width);
// Note here                                        ^

您正在为 width 个字符分配空间,而不是 width 个指针。哎呀

但是,既然你已经用 c++ 标记了它,你为什么不写:

std::vector<std::vector<char>> matR(width, std::vector<char>{height});

(有更好的方法来编写矩阵 class,但这比自己编写 malloc 更好。)

问题出在这样的行上:

matR = (unsigned char**)malloc(sizeof(unsigned char)*width);

matRunsigned char* 的数组,但您只是将它分配为与 unsigned char 的数组一样大。这将分配比实际存储指针所需的内存少 4 或 8 倍的内存,导致您分配的内部数组被错误地指向。