skip to Main Content

I wrote a simple http server in C and I was now trying to send html responses. I wrote a function to read the html file and put it in a string but turns out it’s only working on small .txt files.
I was getting seg faults every time I try to read an html file.
Here’s my code:

int file_to_str(char** string, char* filename){
        FILE* mystream = fopen(filename, "r");
        char c;
        int index = 0;

        *string = (char*) malloc(sizeof mystream);
        
        while ((c = getc(mystream)) != EOF){
                if (c == '"') c = ''';
                (*string)[index++] = c;
        }
        fclose(mystream);
        //string will be freed by the caller
}

2

Answers


  1. You probably are experiencing buffer overrun, unless you happen to read a file smaller than the buffer malloc returns (it can be internally larger than what you request)

    Try the following:

    int file_to_str(char *&string, char* filename)
    {
        FILE* mystream = fopen(filename, "r");
        if (mystream != nullptr)
        {
            fseek(mystream, 0, SEEK_END);
            size_t buf_size = ftell(mystream);
            fseek(mystream, 0, SEEK_SET);
            string = (char *)malloc(buf_size + 10);
            memset(string, 0, buf_size + 10);
            fread(string, sizeof(char), buf_size, mystream);
            fclose(mystream);
        }
    }
    

    Also note: if you aren’t going to return anything, then your return type should be void. Otherwise, you should return a value, maybe the char count? And I used malloc in keeping with your code, but consider an STL container.

    Login or Signup to reply.
  2. FYI: Be careful. Your question has a negative score. I’m afraid to ask another question because they ban users with low scores, and this is a great research space. I think your question is valid and I want to help you, but I just want you to be aware.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search