0

What is wrong with my code? The error says "segmentation fault core dumped"

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

typedef uint8_t  BYTE;

int main(int argc, char* argv[])
{
    // Open the memory card file
    FILE* card = fopen("card.raw", "r");

    if (card == NULL)
    {
        printf("could not open the file. \n");
        return 1;
    }

    //array of bytes
    BYTE ptr[512];

    //image number
    int count = 0;

    //size of the file
    while(fread(ptr, 512, 1, card) == 1)
    {
        if ((ptr[0] == 255 && ptr[1] == 216 && ptr[2] == 255 && ptr[3] == 224) ||(ptr[0] == 255 && ptr[1] == 216 && ptr[2] == 255 && ptr[3] == 225))
        {
            char title[3];
            sprintf(title, "%0.3d.jpg", count);

            //increase image number
            count++;

            //create new image file
            FILE* img = fopen(title, "w");

            int i = 0; //initiate
            do
            {
                //write into the new file
                fwrite(ptr, 512, 1, img);

                i = i + 512;

            }
            while ((ptr[i] != 255 && ptr[i+1] != 216 && ptr[i+2] != 255 && ptr[i+3] != 224) ||(ptr[i+0] != 255 && ptr[i+1] != 216 && ptr[i+2] != 255 && ptr[i+3] != 225));

            //close created image
            fclose(img);
        }
    }

    fclose(card);
    return 0;
}
1

It's a classic buffer overflow error. You store the title of each file in char title[3], but obviously the name of the file is more letters, because it's ['x', 'x', 'x', '.', 'j', 'p', 'g', '\0'], where xxx is the 3 digit number of each image.

But because you overflow your title array, when you try to create the file with this filename, the fopen fails, returning NULL. Then, when you try to write to this file, you get the segfault, because you are trying to write to NULL.

That's the reason why you should always check that the fopen function doesn't return NULL, but it has instead correctly opened/created the file you want. You should do that using the following code:

//create new image file
FILE* img = fopen(title, "w");

if (img == NULL)
{
    printf("Error! Could create the file!\n");
    return 1;
}

Hope this helps you. If this answers your question please accept it by clicking the gray check-mark to the left, so that it becomes green. You can also vote it up by pressing the up arrow above the check-mark.

2
  • For your edited question. I think it's because the condition in your do-while loop. Look at this Answer of a similar Question, and specifically the third item in the list, about De Morgan's law. cs50.stackexchange.com/a/12264/7539
    – ChrisG
    Aug 21 '15 at 19:19
  • And I see you are still not checking for NULL for your file. You should learn from the advice you are given.
    – ChrisG
    Aug 21 '15 at 19:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .