I know this question has already been asked a couple of times, however none of the answers given worked for me. I have a struct with 2 int variables and an unsigned char pointer, and I'm creating a pointer to this struct. Then I want to modify the values of the 2 int variables, and use fread() to take a .raw file (located in the resource files folder, maybe it needs to be elsewhere?) and put it into the unsigned char pointer. However fread() always returns 0, and the program crashes when I try to use free() on the struct pointer. Here's my code so far:
Struct:
typedef unsigned char UCHAR;
struct IMAGERAW
{
int height;
int width;
UCHAR* image;
};
typedef struct IMAGERAW IMAGE;
Main:
int main()
{
IMAGE *img;
img = read_image();
free(img->image);
free(img);
}
read_image():
IMAGE *read_image()
{
IMAGE* img;
FILE* fpI;
int height = 1409;
int width = 1690;
int freadReturn;
fpI = fopen("file.raw", "rb");
img = (IMAGE*)malloc(sizeof(IMAGE));
img->height = height;
img->width= width;
freadReturn = fread(img->image, sizeof(UCHAR), img->height * img->width, fpI);
printf("fread() returns : %d", freadReturn);
fclose(fpI);
return img;
}
The freadReturn variable is always set to 0 (I believe it should be set to height * width), and the program gives an error at the line "free(img->image);". The dimensions are correct, if I change them the program crashes earlier, and so is the file name, so I really don't know what I'm doing wrong. Thanks in advance!
CodePudding user response:
As @BoP mentionned, I somehow forgot to assign memory for the unsigned char pointer of the struct. So I added
img->image = (UCHAR*)malloc(img->height * img->width);
just above the line with fread(), and now fread() returns a correct value.