0

The following was my load() function for pset6 server.c

bool load(FILE* file, BYTE** content, size_t* length)
{
    size_t count = 0;

        BYTE* file_char = malloc(sizeof(BYTE));
        while (fread(file_char, sizeof(BYTE), 1, file))
        {
            count++;
            file_char = realloc(file_char, (count + 1) * sizeof(BYTE));
        }

    *content = file_char;
    *length = count;

    return true;
}

This was not working and on debugging through GDB I noticed that each character read by fread() was being written to the same memory location for every iteration. I solved this by adding the value of count to file_char at each iteration.

bool load(FILE* file, BYTE** content, size_t* length)
{
    size_t count = 0;

        BYTE* file_char = malloc(sizeof(BYTE));
        while (fread(file_char + count, sizeof(BYTE), 1, file))
        {
            count++;
            file_char = realloc(file_char, (count + 1) * sizeof(BYTE));
        }

    *content = file_char;
    *length = count;

    return true;
}

I'm not sure why this was happening. fread() should retain the location where it last left off. So I wanna confirm my doubt, was realloc() resetting fread()'s location pointer here?

2

per fread's man page:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

The function fread() reads nmemb elements of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.

per realloc's man page:

The realloc() function returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and may be different from ptr, or NULL if the request fails.

so the pointer returned by realloc is either ptr or not. in either case, it points to the beginning of the allocated memory block. and since fread stores the data it reads in the location pointed to by ptr, it keeps overriding your data. (see why the problem is fixed by adding the value of counter to your pointer?)

as a side note, you probably shouldn't allocate one more byte in each iteration as this generally slows things down. instead, you probably should introduce a buffer. take a look at how GetString handles this https://github.com/cs50/c/blob/dev/cs50.c#L229!

| improve this answer | |
  • Thanks :) I'll try to implement it like GetString as you have suggested. – Shantanu May 22 '16 at 12:12
  • thanks for the help. can you help specify why sometimes realloc fails, is it because finding contiguous chunk of larger memory is not always feasible? – davyjones Jun 9 '16 at 3:38
  • @davyjones several reasons among which of course is not enough memory. – Kareem Jun 9 '16 at 8:06

You must log in to answer this question.

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