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

时间:2016-05-13 20:26:12

标签: c++ c undefined-behavior

我正在使用malloc分配三个矩阵( matR matG matB )并为它们分配一些矢量的值图像。 像往常一样,我使用两个整数(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
}

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

*显示当i = 100且j = 0时,matR [0] [0]的值变为176。

发生了什么事?

2 个答案:

答案 0 :(得分:2)

这一行:

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});

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

答案 1 :(得分:2)

问题出现在这样的行上:

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

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