Skip to content

Commit

Permalink
Merge pull request #422 from lucasbrg/fix/stbi_image__crash
Browse files Browse the repository at this point in the history
Some optimizations on image.c buffer and stb_image to use less memory.
  • Loading branch information
RobDangerous authored Sep 2, 2019
2 parents 2a19f25 + 910190d commit 5d6d9e5
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
12 changes: 12 additions & 0 deletions Sources/kinc/image.c
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,17 @@
#define BUFFER_SIZE 4096 * 4096 * 4
uint8_t buffer[BUFFER_SIZE];
size_t buffer_offset = 0;
uint8_t *last_allocated_pointer = 0;

static void *buffer_malloc(size_t size) {
uint8_t *current = &buffer[buffer_offset];
buffer_offset += size + sizeof(size_t);
if (buffer_offset > BUFFER_SIZE) {
kinc_log(KINC_LOG_LEVEL_ERROR, "Not enough memory on image.c Buffer.");
return NULL;
}
*(size_t*)current = size;
last_allocated_pointer = current + sizeof(size_t);
return current + sizeof(size_t);
}

Expand All @@ -38,7 +41,16 @@ static void *buffer_realloc(void *p, size_t size) {
return old_pointer;
}
else {
if (last_allocated_pointer == old_pointer){
size_t last_size = &buffer[buffer_offset] - old_pointer;
size_t size_diff = size - last_size;
buffer_offset += size_diff + sizeof(size_t);
return old_pointer;
}
uint8_t *new_pointer = (uint8_t *)buffer_malloc(size);
if (new_pointer == NULL){
return NULL;
}
memcpy(new_pointer, old_pointer, old_size < size ? old_size : size);
return new_pointer;
}
Expand Down
4 changes: 3 additions & 1 deletion Sources/kinc/libs/stb_image.h
Original file line number Diff line number Diff line change
Expand Up @@ -4894,7 +4894,9 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp)
stbi_uc *p;
if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
while (ioff + c.length > idata_limit)
idata_limit *= 2;
//Originally this was idata_limit *= 2. Changed to append a constant size on realloc instead of doubleing everytime.
//This saves some space on the image.c buffer.
idata_limit += 1 << 16;
STBI_NOTUSED(idata_limit_old);
p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory");
z->idata = p;
Expand Down

0 comments on commit 5d6d9e5

Please sign in to comment.