3 c malloc struct segmentation-fault
我还在学习C,并开始使用它来生成图像.我无法弄清楚为什么我的一个程序是segfaulting.这是源代码,减少到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;
}
Run Code Online (Sandbox Code Playgroud)
它编译并运行良好(在Ubuntu和使用Cygwin的Vista上使用gcc),但是取消注释处理img-> o的两行会打破它.我有一种感觉它与之前的问题有关,但是我正在考虑所有需要进行malloc的工作(我认为).任何帮助,将不胜感激.
Jar*_*Par 21
您的malloc语句中存在错误.你正在使用指针而不是结构.这只给你4个字节的内存,而不是你的struct所需的实际大小.
black = malloc(sizeof(*black));
Run Code Online (Sandbox Code Playgroud)
为指针分配内存时,需要为指向的事物分配内存,而不是指针的类型.如果您只是sizeof(*black)如图所示编写,即使black更改类型,您也将始终获得正确的类型.