Felix Rosén February 2016

Segmentation fault on file IO

So my task is to implement a load function for a very simple server. And i cant really figure out where my segmentation fault is. I've tried to use GDB but since i use telnet with which i send http headers as input i've had a hard time with getting any results from it.

the function:

 //Loads a file into memory dynamically allocated on heap.
 //Stores address thereof in *content and length thereof in *length.

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

    char* buffert = malloc(BYTES * sizeof(char));

    while(true)
    {

        // read into buffert
        fread(buffert, BYTES, sizeof(char), file);

        //store the pointer of this buffert in content
        *content = buffert;

        //update length
        length += 1;

        // checks for eof
        if(feof(file) != 0)
        {
            break;
        }
    }

   free(buffert);

   return true;
}

"...BYTE, which we’ve indeed defined as an 8-bit char."

Thx!!

Answers


David Haim February 2016

  *content = buffert;

vs.

   free(buffert);

BYTE** content points to memory which was de-allocated. you probably want to keep this data alive as long as buffert is alive, and deallocate it then.

plus, you probably meant to write length += BYTES , since you are already reading the whole file as once. (also, the while(true) is un-needed)

Post Status

Asked in February 2016
Viewed 3,090 times
Voted 12
Answered 1 times

Search




Leave an answer