0

I seem to be stuck on pset4 recover and would appreciate some help! I think I understand the idea of the problem set by now but I've done approached the problem a bit unconventionally and keep getting a segmentation fault. If somebody could hint at where and how I've gone wrong I'd appreciate it. It's very likely that it has something to do with my conception of when malloc must be used is flawed so some additional enlightenment on that would be nice. I know some people used something with "BYTE" but I'm trying to get firm grasp on malloc. I've also noted three spots I personally think might cause me problems. I don't know if I should post the entire code so here are the relevant bits.

// Declare some variables yeh boii
unsigned char *buffer = malloc(sizeof(buffer));
int counter = 0;
FILE *img = NULL;

// Find the first start of jpeg
bool first_jpeg = false;
do
{   
    // Search 512 byte blocks until start of jpeg is recognized
    fread (buffer, 512, 1, raw_file);
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
    {
        first_jpeg = true;        
    }
}
while (first_jpeg == false);

// MAYBE ADD AN FSEEK HERE TO OFFET THE STEP IT TOOK TO FIND FIRST JPEG??

// Repeat until end of file
while(!feof(raw_file))
{
    // Copy one 512 byte block from raw to buffer
    fread (buffer, 512, 1, raw_file);  // This is where debug50 stops. HERE

    //If start of a jpeg
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
    {
        // Close previous jpeg
        if (counter > 1)
        {
            fclose(img);
        }

        // Create new jpeg
        sprintf(filename, "%03d.jpg", counter);     // HERE?
        img = fopen(filename, "w");
        fwrite(&buffer, sizeof(buffer), 1, img);
        counter++;

    }
    // If part of the jpeg (but not the start of one)
    else
    {
        fwrite(&buffer, sizeof(buffer), 1, img);
    }
}
1

First,

unsigned char *buffer = malloc(sizeof(buffer));

will give you a buffer of size 8 (because sizeof(buffer)) when buffer is a pointer is the size of a pointer (8 bytes). You need a buffer that will hold 512 bytes, so perhaps malloc(512); would be better.

The only time sizeof(buffer) would work in this program is if your buffer were declared as an array of bytes, like: unsigned char buffer[512];

sizeof(buffer) would be 512 in that case.

Keep that in mind later when you are writing.

Second, I'm unclear as to the purpose of your "find first jpg" do/while loop. It seems unnecessary.

You must log in to answer this question.

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