Segmentation fault in C with fread and fwrite even

2019-09-14 00:02发布

问题:

I have been working on a program that keeps crashing due to segmentation fault. I cropped out the simplest part of the code causing this issue. According to what I learnt so far, if I ask the OS for memory allocation, and then use the pointer to read&write to that address of the memory, it should be good to go.

In this case, the following snipped looks pretty simple to me: opening a new file for writing, opening source file, creating outdata to hold enough bytes, reading the exact value of bytes from source and writing to new file with fwrite with same parameters.

Is there something fundamental I'm missing here?

int main (void)
{
    FILE *outimg = fopen("test.jpg", "w");
    FILE *rawFile = fopen("source.file", "r");
    if(rawFile==NULL)
    {
      fprintf(stderr, "Unable to open source file\n");
      return 1;
    }
    int chunkSize = 512;
    int picChunkCount = 440;
    unsigned char *outdata = malloc(chunkSize*picChunkCount*sizeof(unsigned char));
    if(outdata==NULL)
    {
      fprintf(stderr,"Unable to allocate memory for *outdata\n");
      return 2;
    }
    fread(&outdata, sizeof(unsigned char)*chunkSize*picChunkCount,1, rawFile);
    fwrite(&outdata, sizeof(unsigned char)*chunkSize*picChunkCount, 1, outimg);
}

回答1:

Just remove & in fread and fwrite.

That's because outdata already points to location, allocated by malloc().

P.S. Don't forget to free(outdata);



回答2:

Two things are missing:

  • You're reading and writing bytes, so you need to specify fopen parameters to wb and rb
  • Not checking the return of fopen, fwrite and error while memory allocation.

Finally, it's better to allocate memory consistently: if your file weighs 20Gb, but only 10Gb RAM available – something bad will happen.

Try to use this:

#include <stdio.h>
#include <stdlib.h>

#define CHUNK 512

int main () {
    FILE *inputFile;
    FILE *outputFile;
    unsigned char *buffer;
    size_t nread;

    buffer = malloc(CHUNK);
    if (!buffer) exit(1);

    inputFile  = fopen("input.txt", "rb");
    outputFile = fopen("output.txt", "wb");

    if (!inputFile || !outputFile) exit(2);

    while ((nread = fread(buffer, 1, CHUNK, inputFile)) > 0)
        fwrite(buffer, 1, nread, outputFile);

    if (ferror(inputFile) || ferror(outputFile)) exit(3);

    free(buffer);
    fclose(inputFile);
    fclose(outputFile);

    return 0;
}


标签: c file-io malloc