0

Upon further checking, I found that the function load doesn't return true meaning something went wrong somewhere. Am I using fread, realloc and memcpy right?

bool load(FILE* file, BYTE** content, size_t* length)
{
    // initialize content and its length
    *content = NULL;
    *length = 0;
    BYTE buffer[BYTES];

    while(fread(&buffer[0],sizeof(BYTE),BYTES,file) == BYTES)
    {
        // append bytes to content 
        *content = realloc(*content, (*length + BYTES + 1) * sizeof(BYTE)); //Current memory size + buffer + null-terminate
        if (*content == NULL)
        {
            *length = 0;
            break;
        }
        memcpy(*content + *length, buffer, BYTES * sizeof(BYTE));
        *length += BYTES;

        // null-terminate content thus far
        *(*content + *length) = '\0';
    }

    // invalid
    if (*content == NULL)
    {
        free(*content);
        *length = 0;
        return false;
    }
    return true;
}
1

When you use realloc, you want to store the return value in content, not *content. content refers to a pointer, while *content refers to whatever is at the memory address stored in the pointer - and the former is what you intend to modify.

Similarly, the first argument should just be the pointer (content) and not the dereferenced pointer (*content).

It looks like this is also a problem in subsequent lines, for example when you compare *content with NULL.

3
  • Having changed the realloc call to content = realloc(content, (*length + BYTES + 1) * sizeof(BYTE));, I complied server.c and tried to run it. However it seems that there is a problem with the realloc call and I get an error stating *** Error in ./server': realloc(): invalid pointer: 0x00007ffe84bd45b0 *** Aborted`. Any idea what this error means? – Wet Feet Mar 7 '16 at 1:37
  • Having thought over it again, like you said, *content refers to whatever is at the memory address stored in the pointer (in other words, the address of the chunk of memory containing the contents read from file). Isn't that the address realloc needs since it is changing the size of that chunk of memory? – Wet Feet Mar 7 '16 at 11:23
  • Yeah, but realloc need the address, not whatever is in the address. – Levi Roth Mar 8 '16 at 17:26

You must log in to answer this question.

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