0

I implemented the load function, I compiled it without errors, but if I run it with gdb I get segmentation fault, sometimes after the first fread, sometimes after the second. That's my code:

bool load(FILE* file, BYTE** content, size_t* length)
{
    *content = malloc(sizeof(BYTE));
    *content = NULL;
    *length = 0;
    //stores the address of the first byte in *content
    fread(*content, sizeof(BYTE), 1, file);

    if(*content == NULL)
    {
        printf("nothing to load");
        free(*content);
        return false;
    }
    else
        *length = 1;

    BYTE* new_byte = malloc(sizeof(BYTE));
    new_byte = NULL;

    //reads all available bytes from file and stores those bytes contiguously in dynamically allocated memory on the heap
    while(fread(new_byte, sizeof(BYTE), 1, file))
    {
        int i = *length;
        *length = *length + 1;
        *content = realloc(*content, sizeof(BYTE) * (*length));
        *content[i] = *new_byte;
    }
    return true;
}

Can someone help me? Thanks

1

I would expect this to always seq fault on the first read because of this *content = NULL;. It would seg fault on the second read for the same reason (new_byte = NULL;).

NULL is a defined constant and as such is immutable, so you cannot "fread into NULL".

Removing those lines should stop the program from seg faulting.

Addendum

gdb (tips here), or the new debug50! is a great way to find where your program is segfaulting. While you have doubts (is it here? or here?), it would be difficult to decide the fix. It would probably be easiest to use gdb with a curl request rather than a browser request so you don't have to deal with the pesky favicon.ico. cat.html is a good choice because it is 156 bytes (you can see that with an ls -al command in your public directory).

Since you are reading one byte of file into new_byte, perhaps it doesn't have to be (shouldn't be?) a BYTE pointer; it could be a regular old BYTE. That might cause a problem too, with image data. Since a BYTE is cast as a char, and you cannot read image data into a char (info here), you might want to declare it a regular old int.

1
0

Thanks, I understood and corrected the error... but it's still giving me seg fault after few iteration... I think the problem is in the realloc function or in the line *content[i] = *new_byte But I really don't find a way to fix it...

2
  • This should really be entered as a comment, not a new answer. I'll amend the answer. – DinoCoderSaurus Sep 17 '16 at 14:49
  • sorry that's my first post! – Margherita Bonaldi Sep 20 '16 at 12:54

You must log in to answer this question.

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