调用实现

Calloc implementation

我制作了 ft_callocft_memset,它们都有效,但我不明白为什么。

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);
}

我不明白为什么要在 ft_calloc 函数中乘以 nmembsize

示例:

(ft_calloc) nmemb = 5size = 4(ft_memset) size_t n = (5 * 4)、 变量 i 将在 while 循环中过度递增,而我需要在数组的第 5 个元素 (nmemb) 处停止。这是正确的吗?

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

因为ft_memset在字节级别操作,将每个字节设置为给定值。如果每个元素有 nmembsize 字节,则总字节数为 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

不,不会。您正在迭代 unsigned char *。也就是说,每个元素都是一个字节。由于在 ft_calloc 中你有 5 个成员,每个成员的大小为 4 字节,总字节数为 5 * 4 == 20,这意味着如果你使用类型为 [=23= 的指针] 要进行迭代,您需要进行 20 次迭代。代码正确。


注意:正如评论中的 @chux 所述,您应该在 ft_calloc() 之前检查溢出 调用 malloc() 并在 nmemb * size 太大的情况下使函数失败:

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