Search code examples
cmemorycallocmemset

Calloc implementation


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?


Solution

  • I don't understand why multiply nmemb and size in ft_calloc function

    Because ft_memset operates at the byte level, setting every single byte to the given value. If you have nmemb elements of size bytes each, the total number of bytes is nmemb * size.

    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

    No it will not. You are iterating over an unsigned char *. That is, each element is one byte. Since in ft_calloc you have 5 members each of size 4 bytes, the total number of bytes is 5 * 4 == 20, which means if you use a pointer of type unsigned char * to iterate you will need to do 20 iterations. The code is correct.


    NOTE: as @chux states in the comments, you should check for overflow in your ft_calloc() before calling malloc() and make the function fail in case nmemb * size is too large:

    if (size && SIZE_MAX/size < nmemb)
        return NULL;