函数是动态分配内存的库函数。动态意味着内存是在运行时(程序的执行)从堆段分配的。
初始化
malloc() 分配给定大小(以字节为单位)的内存块并返回指向块开头的指针。malloc() 不会初始化分配的内存。如果您尝试从分配的内存中读取而不首先对其进行初始化,那么您将调用undefined behavior,这通常意味着您读取的值将是垃圾。
calloc() 分配内存并将分配内存中的每个字节初始化为 0。如果您尝试读取已分配内存的值而不对其进行初始化,您将得到 0,因为它已经被 calloc() 初始化为 0 .
参数
malloc() 采用单个参数,即要分配的字节数。
与 malloc() 不同,calloc() 有两个参数:
1) 要分配的块数。
2) 每个块的大小(以字节为单位)。
返回值
在 malloc() 和 calloc() 中成功分配后,返回指向内存块的指针,否则返回 NULL,表示失败。
例子
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Both of these allocate the same number of bytes,
// which is the amount of bytes that is required to
// store 5 int values.
// The memory allocated by calloc will be
// zero-initialized, but the memory allocated with
// malloc will be uninitialized so reading it would be
// undefined behavior.
int* allocated_with_malloc = malloc(5 * sizeof(int));
int* allocated_with_calloc = calloc(5, sizeof(int));
// As you can see, all of the values are initialized to
// zero.
printf("Values of allocated_with_calloc: ");
for (size_t i = 0; i < 5; ++i) {
printf("%d ", allocated_with_calloc[i]);
}
putchar('\n');
// This malloc requests 1 terabyte of dynamic memory,
// which is unavailable in this case, and so the
// allocation fails and returns NULL.
int* failed_malloc = malloc(1000000000000);
if (failed_malloc == NULL) {
printf("The allocation failed, the value of "
"failed_malloc is: %p",
(void*)failed_malloc);
}
// Remember to always free dynamically allocated memory.
free(allocated_with_malloc);
free(allocated_with_calloc);
}
输出
Values of allocated_with_calloc: 0 0 0 0 0 The allocation failed, the value of failed_malloc is: (nil)