0x050f/libft-war-machine

ft_calloc test says not_clean when including errno.h

steven42tokyo opened this issue · 2 comments

I'm including errno.h and setting errno = ENOMEM as per the calloc manpage.

Although in some cases malloc will do this for us and it's not necessary, my code checks for overflow after multiplying count and size as follows:

#include <stdlib.h>
#include "libft.h"
#include <errno.h>

void	*ft_calloc(size_t count, size_t size)
{
	size_t	total_count;
	void	*ptr;

	if (count == 0 || size == 0)
	{
		ptr = malloc(1);
		ft_bzero(ptr, 1);
		return (ptr);
	}
	total_count = count * size;
	if (total_count / count != size)
	{
		errno = ENOMEM;
		return (NULL);
	}
	ptr = malloc(total_count);
	if (ptr == NULL)
		return (NULL);
	ft_bzero(ptr, total_count);
	return (ptr);
}

I compared it with actual calloc and it seems that actual calloc does not throw ENOMEM.

#include <stdio.h>
int main ()
{
	char	*foo;

	errno = 0;
	foo = ft_calloc(184467440737095516, 8321713848);
	if (errno == ENOMEM)
		printf("overflow on ft_calloc\n");
	foo = calloc(184467440737095516, 8321713848);
	errno = 0;
	if (errno == ENOMEM)
		printf("overflow on calloc\n");
}