I made a ft_calloc
and ft_memset
, they both work but I don't understand why.
void *ft_memset(void *s, int c, size_t n)
{
size_t i;
unsigned char *p;
i = 0;
p = (unsigned char *)s;
while (i < n)
{
p[i] = (unsigned char)c;
i++;
}
return ((void*)p);
}
void *ft_calloc(size_t nmemb, size_t size)
{
void *s;
if (!(s = malloc(size * nmemb)))
return (NULL);
s = ft_memset(s, 0, nmemb * size);
return (s);
}
I don't understand why multiply nmemb
and size
in ft_calloc
function.
Example:
In (ft_calloc) nmemb = 5
and size = 4
, (ft_memset) size_t n = (5 * 4)
,
the variable i
will over increment in the while
loop, while I need to stop at the 5th element (nmemb
) of the array. Is this correct?
Because
ft_memset
operates at the byte level, setting every single byte to the given value. If you havenmemb
elements ofsize
bytes each, the total number of bytes isnmemb * size
.No it will not. You are iterating over an
unsigned char *
. That is, each element is one byte. Since inft_calloc
you have5
members each of size4
bytes, the total number of bytes is5 * 4 == 20
, which means if you use a pointer of typeunsigned char *
to iterate you will need to do20
iterations. The code is correct.NOTE: as @chux states in the comments, you should check for overflow in your
ft_calloc()
before callingmalloc()
and make the function fail in casenmemb * size
is too large: