读取矩阵,用malloc分配,AddressSanitizer:heap-buffer-overflow

时间:2016-05-29 17:16:57

标签: c matrix header malloc

所以我正在编写一个包含结构像素的矩阵。代码似乎将标准像素写入矩阵,但是当我尝试打印出内容时,它似乎指向错误的地址,因为AddressSanitizer即将出现,printf正在从错误的地址读取: 以下是使用test printf()分配的代码:

#include <stdio.h>
#include <stdlib.h>
#include "matrx.h"
#include "pixel.h"

void matr_initializer(struct matrix* matr, int w, int h){

matr->height = h;
matr->width = w;
struct pixel p;
standardPixel(&p);
matr->grid = (struct pixel**)malloc(sizeof(struct pixel)*w);

if(matr->grid == NULL){
   fprintf(stderr,"Irgendwas lief beim allozieren verkehrt");
   abort();
}

for(int i = 0; i < w; i++){
   matr->grid[i] = (struct pixel*)malloc(sizeof(matr->grid)*h);
}

for(int i = 0; i < w; i++){
   for(int j = 0; j < h; j++){
     matr->grid[i][j] = p;
   /*Here is the printf that causes the error*/
     printf("%d %d %d ",matr->grid[i][j].r,matr->grid[i][j].g,matr->grid[i][j].b);
}
   printf("\n");
}


 matr->n = w*h;
 matr->init = 1;

}

以下是我正在使用的头文件:

 #ifndef _MATRH_
 #define _MATRH_
 #include <stdio.h>
 #include <stdlib.h>
 #include "pixel.h"
 // typedef struct matrix matrix;

 struct matrix{
 int height;
 int width;
 struct pixel*  spalten;
 struct pixel** grid;
 int n;
 int init;
 };

 void matr_initializer(struct matrix* matr, int w, int h);


 void printf_matr_color(struct matrix* matr);

 void printf_matr_RGB(struct matrix* matr);
 #endif

和pixel.h

#ifndef _PIXELH_
#define _PIXELH_
#include <stdio.h>
#include <stdlib.h>

struct pixel{
  int color;
  int r,g,b;
  int brightness;
  int energy;
};

void standardPixel(struct pixel* p);
#endif

1 个答案:

答案 0 :(得分:0)

grid的成员struct matrix被声明为struct pixel **,您似乎打算将其用作动态分配的动态分配数组指针数组。这很好。

您对matr->grid本身的分配很奇怪,尽管本身并不成问题。您为w的{​​{1}}个实例分配了足够的空间,但您实际打算存储的内容是struct pixel 指针w。只要struct pixel至少与struct pixel一样大,分配的空间就够大了,但你真的应该通过分配确保足够大小的空间来避免所有疑问,并且此外并不过分。

您对成员指针struct pixel *指向的空间的分配是更严重的问题所在。对于每一个,您分配matr->grid个字节,但您实际需要的是sizeof(matr->grid)*h个字节。 sizeof(struct pixel) * h很可能大于struct pixelmatr->grid),在这种情况下,您不需要分配尽可能多的内存。

这似乎是你真正想要的:

struct pixel **

此处需要注意的事项:

  • 在C
  • 中转换matr->grid = malloc(sizeof(*matr->grid) * w); for(int i = 0; i < w; i++){ matr->grid[i] = malloc(sizeof(*matr->grid[i]) * h); } /* error checking omitted for brevity */ 的返回值是不必要的且通常是不可取的
  • malloc()运算符不评估其操作数;它只使用操作数的类型(有一个例外,这里不适用)。
  • 因此,如所示,根据指针的参考大小计算要分配的字节数是有效的。这可以确保您使用正确的元素大小,即使您更改了指针的类型。

此外,请注意,虽然您的索引编制似乎与您的分配和尺寸标注一致,但您的网格方式仍由sizeof编制索引。通过[column][row]来安排索引更为典型。