fixed potentiel segfault in malloc.c where I memset ret without checking that ret is not NULL, and used true header size to memsetthe malloc disturb patern, in case malloc allocate a larger chunk than expected

This commit is contained in:
thrieg 2025-12-13 06:39:20 +01:00
parent db2b5f27bb
commit 0384df02e9
2 changed files with 10 additions and 7 deletions

View file

@ -3,10 +3,10 @@
/* ::: :::::::: */
/* main_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: thrieg < thrieg@student.42mulhouse.fr> +#+ +:+ +#+ */
/* By: thrieg <thrieg@student.42mulhouse.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/11/28 17:23:45 by thrieg #+# #+# */
/* Updated: 2025/12/08 15:52:17 by thrieg ### ########.fr */
/* Updated: 2025/12/13 06:24:05 by thrieg ### ########.fr */
/* */
/* ************************************************************************** */
@ -29,7 +29,7 @@ int main(void)
c[i] = i * 2;
write(1, "\n\n\n\n\nafter first alloc: \n\n\n\n\n", sizeof("\n\n\n\n\nafter first alloc: \n\n\n\n\n") - 1);
show_alloc_mem_ex(false);
show_alloc_mem(false);
free(a);
free(b);
@ -52,7 +52,7 @@ int main(void)
write(1, "\n\n\n\n\nafter allocating again: \n\n\n\n\n", sizeof("\n\n\n\n\nafter allocating again: \n\n\n\n\n") - 1);
show_alloc_mem_ex(false);
a = realloc(a, 420); // move the block
a = realloc(a, 5200); // move the block (use "getconf PAGESIZE" to confirm the rounded-up size logic)
c = realloc(c, 504 * sizeof(int)); // expend
b = realloc(b, 400); // shrink

View file

@ -3,10 +3,10 @@
/* ::: :::::::: */
/* ft_malloc.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: thrieg < thrieg@student.42mulhouse.fr> +#+ +:+ +#+ */
/* By: thrieg <thrieg@student.42mulhouse.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/11/17 15:02:55 by thrieg #+# #+# */
/* Updated: 2025/12/08 16:02:22 by thrieg ### ########.fr */
/* Updated: 2025/12/13 06:31:39 by thrieg ### ########.fr */
/* */
/* ************************************************************************** */
@ -33,7 +33,10 @@ void *malloc(size_t size)
ret = add_tiny(size);
}
pthread_mutex_unlock(&g_mut);
if (g_state.patern)
if (ret && g_state.patern)
{
size = (((t_header *)ret) - 1)->size;
ft_memset(ret, g_state.patern, size); // doesn't need to lock because we only modify the user pointer and the user doesn't have accces to it yet
}
return (ret);
}