简体   繁体   中英

Segmentation Fault when reading from raw file

I'm trying to read data from a raw file and storing them in a buffer of type char * that will then be stored in a jpg file and for some reason I keep getting a "Segmentation fault" error.

I'm using the malloc() function to allocate 512 bytes of memory for the buffer but I can only read up to 8 bytes at a time before I get the error (I'm trying to read 512 bytes at once).

Here's my code:

char *rawfilename = argv[1];

FILE *rawfile = fopen(rawfilename, "r");

if(rawfile == NULL)
{
    fprintf(stderr, "Could not open %s.\n", rawfilename);
    return 2;
}

char imgfilename[] = "image0.jpg";

FILE *imgfile = fopen(imgfilename, "w");

char *buffer = malloc(512 * sizeof(char));


//This works

fread(&buffer, 8, 1, rawfile);

fwrite(&buffer, 8, 1, imgfile);

/////////


//This doesn't work

fread(&buffer, 512, 1, rawfile);

fwrite(&buffer, 512, 1, imgfile);

/////////


free(buffer);

fclose(rawfile);

fclose(imgfile);

I've tried googling this problem and searching through Stack overflow but could not find anything that related to this specific issue so my apologies if something like this was already answered. I'm probably doing something stupid or not using something correctly.

Thanks

You are passing the address of the pointer rather than the address which the pointer points to into fwrite and fread which is causing undefined behaviour. You should pass the value of the pointer, ie the address to the block of memory you allocated, to the function.

It should be fread(buffer, 8, 1, rawfile); and not fread(&buffer, 8, 1, rawfile);

Your top example also does not work, undefined behaviour is just... well undefined. If you are lucky it crashes, if not you might get confused.

The comment of Ilya Bursow gives you the answer.

However, the fact that the following works:

fread(&buffer, 8, 1, rawfile);

is beacuse you are on a 64 bit system where pointers are 64 bit. So you told fread to read 8 bytes and put that in the pointer, which is exactly 8 bytes...

And so, reading anything more than 8 bytes in this manner overwrites other memory, causing undefined behavior.

Lookup the descripion of fread . it will tell it needs a pointer to the memory, not the address of the pointer to memory (ie not a pointer to a pointer to memory). And since buffer is already pointer, you only need to write fread(buffer,...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM