私はまだCを学んでおり、それを使って画像を生成し始めました。私のプログラムの 1 つがセグメンテーション違反を起こしている理由がわかりません。ソースコードは次のとおりです。40行に短縮されています。
#include <stdio.h>
#include <stdlib.h>
struct color {
unsigned char r, g, b;
};
struct image {
int w, h/*, o*/;
struct color **data;
};
int main() {
// Declarations
int x, y;
struct color *black;
struct image *img;
// Set up color black
black = (struct color *) malloc(sizeof(struct color *));
black->r = 0;
black->g = 0;
black->b = 0;
// Set up image img
img = (struct image *) malloc(sizeof(struct image *));
img->w = 1;
img->h = 1;
/*img->o = 0;*/
img->data = (struct color **) malloc(img->h * sizeof(struct color *));
for (y = 0; y < img->h; y++) {
img->data[y] = (struct color *) malloc(img->w * sizeof(struct color));
}
// Fill in img with black
for (x = 0; x < img->w; x++) {
for (y = 0; y < img->h; y++) {
img->data[y][x].r = black->r;
img->data[y][x].g = black->g;
img->data[y][x].b = black->b;
}
}
// Free black
free(black);
// Free img
for (y = 0; y < img->h; y++)
free(img->data[y]);
free(img->data); // Segfaults
free(img); // Also segfaults
return 0;
}
コンパイルして正常に実行されますが (Ubuntu では gcc を使用し、Cygwin を使用する Vista では)、img->o を扱う 2 行のコメントを外すと、問題が発生します。この前の質問に関連していると感じていますが、mallocする必要があるものはすべてmallocしています(と思います)。どんな助けでも大歓迎です。