Skip to content

TODO: dynamic buffer handling to never overflow #3

Description

@EmilioSchi

My solution works with small BUFFERSIZE value... but now i lose lastest bytes

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "html.h"

#define BUFFSIZE 2

int main(int argc, char **argv) {
    //TODO: dynamic buffer handling to never overflow
    FILE *f;
    HtmlDocument *doc;
    HtmlParseState *parse_state;

    char *buf = NULL; 
    buf = (char*) realloc (buf, (BUFFSIZE+1) * sizeof(char));
    buf[BUFFSIZE] = 0;

    const char *token = buf;


    if(argc != 2) {
        fprintf(stderr, "usage: html <file.html>\n");
        return 1;
    }

    size_t len = 0;
    size_t buffsize = BUFFSIZE;

    parse_state = html_parse_begin();
    if(!(f = fopen(argv[1], "r"))) {
        fprintf(stderr, "error: cannot open file %s\n", argv[1]);
        return 1;
    }

    int gain=0;
    int aftergain=0;
    int add=0;

    while(!feof(f)) {
        if (buffsize==0) {
                gain++;
                add=1;
                buf = (char*) realloc (buf, (gain+BUFFSIZE + 1) * sizeof(char));
                buf[gain+BUFFSIZE] = 0;
        } else {
            add = 0;
        }
        len = fread(buf+(BUFFSIZE+aftergain-buffsize), 1, add+buffsize, f);
        token = html_parse_stream(parse_state, buf + (BUFFSIZE+aftergain-buffsize), buf, len);
        buffsize = (token - buf);
        memmove(buf, token, BUFFSIZE+gain-buffsize);
        aftergain=gain;

    }

    doc = html_parse_end(parse_state);
    fclose(f);

    html_print_dom(doc);

    html_free_document(doc);

    free(buf);
    return 0;
}

Check this pls

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions