fix: potential buffer overflow caused by missing terminating null byte in t_buffer

This only occurs in specific circumstances where the number of bytes to be added
to a t_buffer via the ft_buffer_push_buf function is exactly equal to the number
of free bytes in the current underlying buffer. This does not occur if the
number of bytes to add to the buffer is smaller than that, since we allocate new
space using ft_calloc.

In these circumstances, since no terminating null byte is added, other code may
read past the end of the buffer, causing a buffer overflow.
This commit is contained in:
Khaïs COLIN 2025-04-09 17:25:48 +02:00
parent 3ec90f7770
commit 82da182773
Signed by: logistic-bot
SSH key fingerprint: SHA256:RlpiqKeXpcPFZZ4y9Ou4xi2M8OhRJovIwDlbCaMsuAo

View file

@ -6,7 +6,7 @@
/* By: kcolin <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/12/12 12:39:58 by kcolin #+# #+# */
/* Updated: 2025/03/10 18:45:34 by khais ### ########.fr */
/* Updated: 2025/04/09 17:26:24 by khais ### ########.fr */
/* */
/* ************************************************************************** */
@ -84,6 +84,8 @@ t_buffer *ft_buffer_pushchar(t_buffer *buffer, char c)
/*
** push buf to the end of buffer, growing buffer if needed.
**
** also adds an additional null byte to terminate the buffer.
**
** the number of bytes to copy to buffer is n.
** returns buffer.
** in case of error, all memory is freed and null is returned.
@ -92,7 +94,7 @@ t_buffer *ft_buffer_push_buf(t_buffer *buffer, char *buf, size_t n)
{
if (buffer == NULL)
return (NULL);
while (buffer->length + n > buffer->capacity)
while (buffer->length + n + 1 > buffer->capacity)
{
buffer = ft_buffer_grow(buffer);
if (buffer == NULL)
@ -100,5 +102,6 @@ t_buffer *ft_buffer_push_buf(t_buffer *buffer, char *buf, size_t n)
}
ft_memcpy(buffer->buffer + buffer->length, buf, n);
buffer->length += n;
buffer->buffer[buffer->length] = '\0';
return (buffer);
}