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

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        return 1;
    }
    FILE *memory_card = fopen(argv[1], "r");
    if (!memory_card)
    {
        return 1;
    }

    int x;
    x = 0;
    char *filename;
    filename = 0;
    FILE* img = fopen("000.jpg", "w");
    while (feof(memory_card) == 0)
    {
        unsigned char bytes[512];
        fread(bytes, 1, 512, memory_card);
        if (bytes[0] == 0xff && bytes[1] == 0xd8 && bytes[2] == 0xff)
        {
            if (x == 0)
            {
                fwrite(bytes, 1, 512, img);
                x++;
            }
            else
            {
                fclose(img);
                sprintf(filename, "%03i.jpg", x);
                img = fopen(filename, "w");
                fwrite(bytes, 1, 512, img);
                x++;
            }
        }
        else
        {
            if (x > 0)
            {
                fwrite(bytes, 1, 512, img);
            }
        }
    }
    fclose(img);
    fclose(memory_card);
}
  • Have you identified which line of code is causing the seg fault? Learning to do so is an extremely critical skill that you really need to gain! – Cliff B Jun 10 at 3:19
1

Yes, you have already figured it out. filename is not initialized wit a legit memory address. change it to

char filename[16];

and remove the filename = 0;

In case you get more segfaults, you can use this link to debug it. Just click "Start" to run your code.

| improve this answer | |

You must log in to answer this question.

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