这是一个旨在使用ppm图像文件的程序。
尝试从文件中读取图像并将该图像分配给我的全局结构图像时,我遇到了分段错误。
这些是我的ppmIO.c文件的相关部分:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <ppmIO.h>
struct Image *instance;
void ImageRead(char *filename)
{
printf("hi 0!");
int width, height, num, size;
//unsigned char *p;
//Image *image = (Image *) malloc(sizeof(Image));
FILE *fp = fopen(filename, "r");
//if (!image) die("cannot allocate memory for new image");
if (!fp) die("cannot open file for reading");
readPPMHeader(fp, &width, &height);
size = width * height * 3;
printf("hi!");
//instance->data = (unsigned char *) malloc(size);
printf("hi 2!");
instance->width = width;
printf("hi 3!");
instance->height = height;
printf("hi 4!");
if (!instance->data) die("cannot allocate memory for new image");
num = fread((void *) instance->data, 1, (size_t) size, fp);
if (num != size) die("cannot read image data from file");
fclose(fp);
}
这是我的ppmIO.h文件:
#ifndef PPMIO_H
#define PPMIO_H
struct Image
{
int width;
int height;
unsigned char *data;
};
extern struct Image *instance;
//extern Image *ImageCreate(int width, int height);
//extern void ImageClear(struct Image *image, unsigned char red, unsigned char green, unsigned char blue);
extern void ImageRead(char *filename);
extern void ImageWrite(char *filename);
extern void ImageSetPixel(int x, int y, int chan, unsigned char val);
extern unsigned char ImageGetPixel(int x, int y, int chan);
#endif /* PPMIO_H */
这是GDB报告的分段错误:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400fff in ImageRead (filename=0x7fffffffdc32 "nika.ppm")
at ppmIO.c:126
126 instance->width = width;
我认为我试图使用Image *instance
的方式存在问题...但我真的不知道造成这种混乱的原因。 :(