diff --git a/parser.c b/parser.c index 225e752..bb0ff46 100644 --- a/parser.c +++ b/parser.c @@ -114,25 +114,32 @@ HE_face *parse_obj(char const * const filename) static char *read_file(char const * const filename) { char buf[STD_FILE_BUF], - *string = malloc(STD_FILE_BUF); + *string = NULL; int objfile = 0; size_t str_size = 0; ssize_t n; - uint8_t i = 0; objfile = open(filename, O_RDONLY); if (objfile) { /* read and copy chunks */ while ((n = read(objfile, buf, STD_FILE_BUF)) > 0) { - char *tmp_ptr = string + str_size; - memcpy(tmp_ptr, buf, STD_FILE_BUF); - str_size += n; - string = realloc(string, str_size); - i++; + char *tmp_ptr = NULL; + + str_size += n; /* count total bytes read */ + + tmp_ptr = realloc( /* allocate correct size */ + string, /* pointer to realloc */ + str_size /* total bytes read */ + + 1); /* space for trailing NULL byte */ + CHECK_PTR_VAL(tmp_ptr); + string = tmp_ptr; + + /* append buffer to string */ + memcpy(string + (str_size - n), buf, n); } /* add trailing NULL byte */ - string[str_size + 1] = '\0'; + string[str_size] = '\0'; close(objfile);