Search code examples
cstdio

Why does this fread segfault


I have tried many things to fix this segfault issue, I'm not sure whats happening wrong because from my understanding, the fread line should not segfault

// ensure proper usage
    if (argc != 2)
    {
        fprintf(stderr, "Usage: ./recover file");
        return 1;
    }

    char* recover = argv[1];
    // open input file
    FILE * raw_file = fopen(recover, "r");
    if (raw_file == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", recover);
        return 2;
    }

    //somehow read the file

    int counter = 1;
    char file[2];
    sprintf(file,"%03i.jpg",counter);

    int buffer[512];

    //read file and put into buffer
    int*bf = malloc(sizeof(int));
    fread(bf, sizeof(int), 1, raw_file);

Solution

  • you smashed you stack in this block prior to your fread

    char file[2];
    sprintf(file,"%03i.jpg",counter);
    

    file is to small to hold the number of characters you are formatting into it.