Search code examples
cfilesegmentation-faultfread

When I use fread with a 34 mb .mp4 file I get a segmentation fault, how can I solve it?


I'm trying to write code that can reverse a file to make it unreadable. I did this in Python and I'm trying to do it again in C, but when I use fread to read a large file I get a segmentation fault (with files with 1 or 2 mb this doesn't happen), is there anything I can do to solve this?

I tried with this code:

#include <stdio.h>
#include <conio.h>

int main()
{
    FILE *fh=fopen("vid.mp4","rb");
    FILE *fh1=fopen("vid1.png","wb");

    int fsize=36886031;
    char data[fsize];

    fread(data,fsize,1,fh); //<-- error
    fwrite(data,fsize,1,fh1); //<-- error too
}

And i get:

Segmentation fault [Progam finished]


Solution

  • When you declare a variable inside a function like this, you're declaring it on the stack. It is big enough to hold a lot of normal variables, but it usually doesn't have enough memory to hold big arrays. If you want to store big objects, you must use malloc.

    Here, I've modified your code to not crash.

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        FILE *fh=fopen("vid.mp4","rb");
        size_t fsize = 36886031;
        char *data = malloc(fsize);
        if (data == NULL) {
            fprintf(stderr, "Not enough memory");
            return EXIT_FAILURE;
        }
    
        fread(data, fsize, 1, fh);
        free(data); // Don't forget to free this memory
        return EXIT_SUCCESS;
    }
    

    I highly recommend reading about dynamic memory allocation, because it is a very important part of C language.