0

My program works fine for 4 images. They are completely viewable! However, on the 5th run through recursion, it segfaults. Here is the recursion function:

FILE* write(FILE* in_file, FILE* out_file, int image_num, bool writing)
{
BYTE block[512];
fread(block, BLOCK_SIZE, 1, in_file);
if (image_num == 49)
{
    fclose(out_file);
    fclose(in_file);
    return out_file;
}
// search for starting bytes of a jpg file
if (block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff)
{
    bool is_a_jpg = false;
    // double-check fourth block
    for (int j = 0; j < 16; j++)
    {
        if (block[3] == 0xe0 + j)
        {
            is_a_jpg = true;
            break;
        }
    }
    if (is_a_jpg)
    {
        // close open files before starting a new one
        if (writing)
        {
            fclose(out_file);
            printf("Saving file #%.3d.jpg\n", image_num);
            image_num += 1;
        }
        writing = true;
        // create a new jpg file
        char filename[7];
        sprintf(filename, "%.3d.jpg", image_num);
        out_file = fopen(filename, "w");
    }
}
if (writing)
{
    fwrite(&block, BLOCK_SIZE, 1, out_file);
}
return write(in_file, out_file, image_num, writing);
}

Valgrind reports a stack overflow

==2316== Stack overflow in thread 1: can't grow stack to 0xffe801e68
==2316== 
==2316== Process terminating with default action of signal 11 (SIGSEGV)
==2316==  Access not within mapped region at address 0xFFE801E68
==2316==    at 0x42D661: write (recover.c:40)
==2316==  If you believe this happened as a result of a stack
==2316==  overflow in your program's main thread (unlikely but
==2316==  possible), you can try to increase the size of the
==2316==  main thread stack using the --main-stacksize= flag.
==2316==  The main thread stack size used in this run was 8388608.
==2316== Stack overflow in thread 1: can't grow stack to 0xffe801e60

This points to the fread line, and debug50 shows the same problem spot. I'm assuming this all means I am somehow using too much memory, but I don't know how to free up the memory as I go. I am closing each output file when it is complete, so those shouldn't be still taking up space.

EDIT

I tried changing BYTE block[512]; to BYTE* block = malloc(512); and then free(block) right before the recursion. This solution let it run for 47 images before the same segfault/stack overflow. However, now the image files are not valid!

0

Well, I somehow solved this by moving all the code from a recursive function to a while loop. While this allows me to proceed, I'd still love to know if someone can explain why the recursion didn't work.

You must log in to answer this question.

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