0

My load function doesn't seem to load any image, but it always says "200 OK". For example: cat.jpg doesn't load in the browser, but the message with OK always shows up. Code:

bool load(FILE* file, BYTE** content, size_t* length)
{
    if (file == NULL)
    {
        return false;
    }

    char* ptr = malloc(BYTES);

    while (true)
    {
        fread(ptr, BYTES, 1, file);
        *content = ptr;
        *length += BYTES;
        if (feof(file))
        {
            break;
        }
    }
    return true;
}
0

there are many problems that I could spot in your code:

  1. ptr is a temporary buffer. it doesn't really have to have memory allocated for it on the heap. generally, you shouldn't allocate memory on the heap, unless you have to.

    following that, you should probably define ptr as BYTE array as well as give it a more descriptive name (e.g., buffer).

  2. a main problem is that the line *content = ptr does not append the data pointed to by ptr to the data pointed to by *content. rather, it assigns ptr (the address value it stores, not the data it points to) to *content. watch the short on Dynamic Memory Allocation!

    since per the specs, load should dynamically allocate memory on the heap for the data it loads, this memory should be allocated for *content. perhaps an easy way to achieve that is to allocate memory for *content using realloc (see man realloc) and use some simple pointer arithmetic.

  3. another main problem is that you are not handling EOF very well. what happens if the call to fread didn't read any data because there are no more data? should you still try to append data to *content and update *length?

4
  • Thanks a lot for the answer! Well, I followed your tips (made ptr a BYTE* and changed its name to buffer, made buffer = NULL, reallocated *content with *content = realloc(*content, BYTES), assigned *buffer to *content and put the if in the end of the loop), but it doesn't compile. It tells me to remove the * from the buffer when I assign it to content. Can you help me? – Lúcio Cardoso Jun 2 '16 at 16:38
  • @LúcioCardoso I meant BYTE array instead of char *. apologies! – kzidane Jun 2 '16 at 17:03
  • I don't get it. Why should the pointer be an array? – Lúcio Cardoso Jun 3 '16 at 9:28
  • your char * is actually an array of chars malloc'd on the heap, isn't it? – kzidane Jun 3 '16 at 9:31

You must log in to answer this question.

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