Fix memory allocation read_file()

The logic was simply broken and did only work
if the file was less than STD_FILE_BUF.
This commit is contained in:
hasufell 2014-05-07 21:10:07 +02:00
parent 6270173331
commit bc2a35cd4e
No known key found for this signature in database
GPG Key ID: 220CD1C5BDEED020

View File

@ -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);