Home > database >  CS50 Recover - memory issue
CS50 Recover - memory issue

Time:07-21

I'm a bit stymied by this problem, so I'd love any advice or insight into what I'm doing wrong.

In short, when submitting the below Recover code to CS50's CHECK50, I pass every test except the last one. Instead, I get this error in the CHECK50 terminal:

checking that program exited with status 0...checking for valgrind errors...
472 bytes in 1 blocks are still reachable in loss record 1 of 1: (file: recover.c, line: 28)

That error seems straightforward to me. I'm allocating something in memory that I'm not freeing by the end of the code. Here's the operation at line 28 that that the error readout is pointing to:

FILE *mem_card = fopen(argv[1], "r");

From that, I thought all I would have to do is is free(mem_card); at the end of recover.c. However, doing that gave me a huge amount of new Valgrind errors. So I'm a bit stuck and not sure how to approach this, as I don't know what I'm doing wrong.

I've removed the comments from my recover.c code and included it here for more context:

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

typedef uint8_t BYTE;

int main(int argc, char *argv[])
{
    int BLOCK_SIZE = 512;
    int jpeg_count = 0;
    BYTE buffer[BLOCK_SIZE];

    FILE *img;

    if (argc != 2)
    {
        printf("Usage: ./recover IMAGE\n");
        return 1;
    }

    FILE *mem_card = fopen(argv[1], "r"); // CHECK50/Valgrind issue here
    if (mem_card == NULL)
    {
        printf("Could not open for reading %s.\n", argv[1]);
        return 1;
    }

    char filename[8] = {};

    while (fread(buffer, 1, BLOCK_SIZE, mem_card) == BLOCK_SIZE)
    {
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {

            sprintf(filename, "i.jpg", jpeg_count);

            if (jpeg_count == 0)
            {
                jpeg_count  ;

                img = fopen(filename, "w");
                fwrite(buffer, 1, BLOCK_SIZE, img);
            }
            else if (jpeg_count > 0)
            {
                jpeg_count  ;

                fclose(img);
                img = fopen(filename, "w");
                fwrite(buffer, 1, BLOCK_SIZE, img);
            }
        }
        else if (jpeg_count > 0)
        {
            fwrite(buffer, 1, BLOCK_SIZE, img);

        }
        else
        {

        }
    }
    fclose(img);
    //free(mem_card);
    return 0;
}

CodePudding user response:

You opened the file and saved its file pointer to mem_card.

Therefore, you should close the file:

fclose(mem_card);
  • Related