所以我写了一个矩阵,其中包含一个结构像素。该代码似乎将标准像素写入矩阵,但是当我尝试打印出内容时,它似乎指向了错误的地址,因为AddressSanitizer即将出现,即printf正在从错误地址读取: 这里是该代码与测试的printf()分配:从矩阵读取,分配malloc,AddressSanitizer:堆缓冲区溢出
#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
理想情况下,这可以通过使用gdb来解决。但是你可以通过做'matr-> grid =(struct pixel *)malloc(sizeof(struct pixel)* w * h);''来让你的生活更轻松。你认为'sizeof(matr-> grid)* h'的作用是什么? – James
这是真的,我已经想过,但现在好奇,为什么这是行不通的,它似乎没有任何问题 –