rsys

Basic data structures and low-level features
git clone git://git.meso-star.fr/rsys.git
Log | Files | Refs | README | LICENSE

commit 5739a78ea8262d314c11807aa277c6e93b544e22
parent ea5b0b5fd3904cc7c2054cd9e7aa411060a22709
Author: vaplv <vaplv@free.fr>
Date:   Fri, 13 Jul 2018 11:39:08 +0200

Fix possible memory access violations in mem_[re]alloc

On windows, the memory returned by _aligned_offset_malloc was used
without testing that the allocation does not failed.

Diffstat:
Msrc/mem_allocator.c | 24+++++++++++++++---------
1 file changed, 15 insertions(+), 9 deletions(-)

diff --git a/src/mem_allocator.c b/src/mem_allocator.c @@ -50,21 +50,25 @@ mem_alloc(const size_t size) if(size) { #if defined(OS_UNIX) || defined (OS_MACH) mem = malloc(size); + if(mem) { + ATOMIC_ADD(&g_alloc_counter.allocated_size, mem_size(mem)); + ATOMIC_INCR(&g_alloc_counter.nb_allocs); + } #elif defined(OS_WINDOWS) const size_t DEFAULT_ALIGNMENT = 16; mem = _aligned_offset_malloc (size + MEM_HEADER_SIZE, DEFAULT_ALIGNMENT, MEM_HEADER_SIZE); - ((size_t*)mem)[0] = DEFAULT_ALIGNMENT; - ((size_t*)mem)[1] = size + MEM_HEADER_SIZE; - mem = ((char*)mem) + MEM_HEADER_SIZE; + if(mem) { + ((size_t*)mem)[0] = DEFAULT_ALIGNMENT; + ((size_t*)mem)[1] = size + MEM_HEADER_SIZE; + mem = ((char*)mem) + MEM_HEADER_SIZE; + ATOMIC_ADD(&g_alloc_counter.allocated_size, mem_size(mem)); + ATOMIC_INCR(&g_alloc_counter.nb_allocs); + } #else #error "Unsupported OS" #endif } - if(mem) { - ATOMIC_ADD(&g_alloc_counter.allocated_size, mem_size(mem)); - ATOMIC_INCR(&g_alloc_counter.nb_allocs); - } return mem; } @@ -101,8 +105,10 @@ mem_realloc(void* mem, const size_t size) mem = ((char*)mem) - MEM_HEADER_SIZE; new_mem = _aligned_offset_realloc (mem, size + MEM_HEADER_SIZE, ((size_t*)mem)[0], MEM_HEADER_SIZE); - ((size_t*)new_mem)[1] = size + MEM_HEADER_SIZE; - new_mem = ((char*)new_mem) + MEM_HEADER_SIZE; + if(new_mem) { + ((size_t*)new_mem)[1] = size + MEM_HEADER_SIZE; + new_mem = ((char*)new_mem) + MEM_HEADER_SIZE; + } #elif defined(OS_UNIX) || defined(OS_MACH) new_mem = realloc( mem, size ); #else