c - 将 malloc 初始化为零,而不是使用 calloc

标签 c

我想使用 malloc 在堆中创建动态数组。

int *c = malloc(5 * sizeof(int));

问题是它初始化为零,我想尽可能避免使用calloc,因为我不知道它有多安全.

如果我使用calloc,它会执行相同的malloc 工作吗?

最佳答案

ma​​lloc():

malloc() 有一个争论:要分配的字节数。分配的字节未初始化。因此,它们的值可以是 0-255 之间的任何值,或这些数字的任意组合。 不要指望任何事情!

代码示例:

int *mem = malloc(5 * sizeof(int));

<小时/> calloc():

calloc() 有两个参数:要为其分配内存的元素数量以及需要为每个元素分配的内存数量。它将每个字节初始化为零。

代码示例:

int *mem = calloc(5, sizeof(int));

来自C 编程语言 ~ Brian W. Kernighan 和 Dennis M. Ritchie:

void *calloc(size_t nobj, size_t size)
calloc returns a pointer to space for an array of nobj objects,
each of size size, or NULL if the request cannot be satisfied.
The space is initialized to zero bytes.

[强调我的]

<小时/>

或者,您可以使用 memset() 初始化内存

#include <string.h> // for memset()

//allocate memory
int *mem = malloc(5 * sizeof(int));

//initialize memory to zeros
memset(mem, 0, 5 * sizeof(int));

关于c - 将 malloc 初始化为零,而不是使用 calloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39381237/

相关文章:

c - 如何通过汇编代码找到固定长度的多维数组?

c - 如何更安全地编写此 C 片段?

c - 我无法在 char 上使用 strtok

c - 测量信号的持续时间

c++ - 多参数树遍历

c - 尝试将值复制到指针 str 时获取 null

c - execl 和 execv 有什么区别?

c++ - 为什么我的代码块上没有显示输出?

c - 反转半字节

c - 如何使用 c 在控制台中水平打印带有链接的树