0

Below is the function createjpg() I wrote for recover.c of pset4. I have written

void createjpg (void)
{
// opening card.raw
FILE* inptr = fopen("card.raw", "r");

// ensuring that the desired file has opened
if(inptr == NULL)
{
    printf("Could not open card.raw");
    return;
}

// creating a buffer
BYTE* buffer = malloc(512);

// counter to keep track of number of files
int count = 0;

char title[3];

while(fread(buffer, 512, 1, inptr) == 1)
{
    if(*(buffer) == 0xff && *(buffer + 1) == 0xd8 && *(buffer + 2) == 0xff && (*(buffer + 3) == 0xe0 || *(buffer + 3) == 0xe1))
    {
        count ++;
        sprintf(title, "%.3d.jpg", count);
        FILE* img = fopen(title, "w");
        fwrite(buffer, 512, 1, img);
        while(!(feof(inptr)))
        {
            fread(buffer, 512, 1, inptr); // SEGMENTATION FAULT OCCURRING HERE
            if(!(*(buffer) == 0xff && *(buffer + 1) == 0xd8 && *(buffer + 2) == 0xff && (*(buffer + 3) == 0xe0 || *(buffer + 3) == 0xe1)))
            {
                fwrite(buffer, 512, 1, img);
            }
            else
            {
                break;
            }
        }
        if(!(feof(inptr)))
        {
            fseek(inptr, -512, SEEK_CUR);
            fflush(inptr);
            fclose(img);
        }
        else
        {
            break;
        }
    }
}

fclose (inptr);
free(buffer);
}

I have run GDB and it says that Segmentation fault is occurring at fread() which is inside the inner while loop. What am I doing wrong here? Please help

2
FILE* img = fopen(title, "w");

// SEGMENTATION FAULT OCCURRING REALLY HERE

This is because char title [3] does not have enough space to store the title, change it to char title [8] for example

1
  • As MARS suggested, modify the size of your title[] array. You are trying to store 8 bytes (0,0,0,.,j,p,g,\0) in a 3-byte variable, thus accessing memory you should not be accessing.
    – dmorali
    Jul 25 '16 at 0:02

You must log in to answer this question.

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