libm/stdlib: don't read past source in nano_realloc

Save the computed block size and use it to avoid reading past
the end of the source block.

Signed-off-by: Keith Packard <keithp@keithp.com>
This commit is contained in:
Keith Packard via Newlib 2020-08-13 17:19:01 -07:00 committed by Corinna Vinschen
parent 70d02aaca6
commit ce4044adee
1 changed files with 4 additions and 2 deletions

View File

@ -466,6 +466,7 @@ void * nano_realloc(RARG void * ptr, malloc_size_t size)
{ {
void * mem; void * mem;
chunk * p_to_realloc; chunk * p_to_realloc;
malloc_size_t old_size;
if (ptr == NULL) return nano_malloc(RCALL size); if (ptr == NULL) return nano_malloc(RCALL size);
@ -477,13 +478,14 @@ void * nano_realloc(RARG void * ptr, malloc_size_t size)
/* TODO: There is chance to shrink the chunk if newly requested /* TODO: There is chance to shrink the chunk if newly requested
* size is much small */ * size is much small */
if (nano_malloc_usable_size(RCALL ptr) >= size) old_size = nano_malloc_usable_size(RCALL ptr);
if (old_size >= size)
return ptr; return ptr;
mem = nano_malloc(RCALL size); mem = nano_malloc(RCALL size);
if (mem != NULL) if (mem != NULL)
{ {
memcpy(mem, ptr, size); memcpy(mem, ptr, old_size);
nano_free(RCALL ptr); nano_free(RCALL ptr);
} }
return mem; return mem;