【问题标题】:Segmentation Fault within my code我的代码中的分段错误
【发布时间】:2018-07-29 06:26:13
【问题描述】:

这段代码给了我一个段错误

image_t* removeNoiseAverage(image_t* img[]) {

    image_t* average = (image_t*) malloc(sizeof(image_t));

    int image_size = img[0]->header.HEIGHT * img[0]->header.WIDTH;
    int i,k;
    double avg = 0;
    for (i=0;i<image_size;i++){
        avg = 0;
        for (k=0;k<10;k++){
            avg += img[k]->pixels[i].R;
        }
        avg = avg/10;
        average->pixels[i].R = avg;
    }

    return 0;
}

typedef struct image {
  header_t header;      // 15 bytes
  pixel_t* pixels;      // 4 bytes
} image_t;

typedef struct pixel {
  uint8_t R, G, B;
} pixel_t;

typedef struct header {
  char MAGIC_NUMBER[3];
  unsigned int HEIGHT, WIDTH, MAX_COLOR;
} header_t;

image_t 是我创建的结构,分段错误发生在average-&gt;pixels[i].R = avg;

我是不是 malloc 不正确?

编辑:更新以添加声明

【问题讨论】:

  • 你怎么知道pixels数组在image_t中有多大?在分配average 之后的行之前,您不会计算数组的大小。
  • 更新帖子

标签: c pointers segmentation-fault malloc


【解决方案1】:
image_t* average = (image_t*) malloc(sizeof(image_t));

这会为average 分配空间,但不会为其中的average-&gt;pixels 分配空间。两个指针意味着你需要两次分配。

average->pixels = malloc(image_size * sizeof(pixel_t));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多