fix realloc size detection when new size is larger than current chunk max size, add pthread mutex to make the functions thread safe
This commit is contained in:
@ -6,7 +6,7 @@
|
||||
/* By: tomoron <tomoron@student.42angouleme.fr> +#+ +:+ +#+ */
|
||||
/* +#+#+#+#+#+ +#+ */
|
||||
/* Created: 2024/12/02 14:41:22 by tomoron #+# #+# */
|
||||
/* Updated: 2024/12/04 18:50:45 by tomoron ### ########.fr */
|
||||
/* Updated: 2024/12/05 17:32:25 by tomoron ### ########.fr */
|
||||
/* */
|
||||
/* ************************************************************************** */
|
||||
|
||||
@ -20,11 +20,15 @@ static void *realloc_recreate(t_alloc *alloc, size_t size)
|
||||
{
|
||||
void *new;
|
||||
|
||||
pthread_mutex_unlock(&g_mallock);
|
||||
new = malloc(size);
|
||||
pthread_mutex_lock(&g_mallock);
|
||||
if (alloc->size < size)
|
||||
size = alloc->size;
|
||||
pthread_mutex_unlock(&g_mallock);
|
||||
ft_memcpy(new, alloc + 1, size);
|
||||
free(alloc + 1);
|
||||
pthread_mutex_lock(&g_mallock);
|
||||
return (new);
|
||||
}
|
||||
|
||||
@ -44,8 +48,8 @@ static void *realloc_prealloc(t_alloc *alloc, t_mem_chunk *chunk, \
|
||||
alloc->size = size;
|
||||
return (alloc + 1);
|
||||
}
|
||||
if ((size > (size_t)TINY_CHUNK_SIZE && is_small == 0)
|
||||
|| (size > SMALL_CHUNK_SIZE && is_small == 1)
|
||||
if ((size > (size_t)TINY_MALLOC && is_small == 0)
|
||||
|| (size > SMALL_MALLOC && is_small == 1)
|
||||
|| (t_ul)(alloc->next) - (t_ul)(alloc + 1) < size)
|
||||
return (realloc_recreate(alloc, size));
|
||||
chunk->space_left -= size - alloc->size;
|
||||
@ -69,11 +73,12 @@ void *realloc(void *ptr, size_t size)
|
||||
if (!ptr)
|
||||
return (malloc(size));
|
||||
alloc = (t_alloc *)ptr - 1;
|
||||
pthread_mutex_lock(&g_mallock);
|
||||
ptr = realloc_prealloc(alloc, g_allocs.tiny, 0, size);
|
||||
if (ptr)
|
||||
return (ptr);
|
||||
ptr = realloc_prealloc(alloc, g_allocs.small, 1, size);
|
||||
if (ptr)
|
||||
return (ptr);
|
||||
return (realloc_large(alloc, size));
|
||||
if(!ptr)
|
||||
ptr = realloc_prealloc(alloc, g_allocs.small, 1, size);
|
||||
if(!ptr)
|
||||
ptr = realloc_large(alloc, size);
|
||||
pthread_mutex_unlock(&g_mallock);
|
||||
return(ptr);
|
||||
}
|
||||
|
Reference in New Issue
Block a user