gpt4 book ai didi

c - malloc 和 calloc 在使用上的区别

转载 作者:太空宇宙 更新时间:2023-11-04 05:03:12 25 4
gpt4 key购买 nike

gcc 4.5.1 c89

为了更好地理解 malloc 和 calloc,我编写了这个源代码。

我明白了,但有几个问题。

dev = malloc(number * sizeof *devices);

等于这个 calloc。我不关心清除内存。

dev = calloc(number, sizeof *devices);

与在 while 循环中执行 5 次相比,这到底是什么:

dev = malloc(sizeof *devices);

我猜第一个和第二个是创建一个指向 5 struct device 的指针。第三个是创建指向结构设备的单个指针?

我的程序说明了使用 valgrind --leak-check=full 编译和运行的这 3 种不同方法。

非常感谢您的任何建议。

#include <stdio.h>
#include <stdlib.h>

struct Devices {
#define MAX_NAME_SIZE 80
size_t id;
char name[MAX_NAME_SIZE];
};

struct Devices* create_device(struct Devices *dev);
void destroy_device(struct Devices *dev);

int main(void)
{
size_t num_devices = 5;
size_t i = 0;
struct Devices *device = NULL;
struct Devices *dev_malloc = NULL;
struct Devices *dev_calloc = NULL;

for(i = 0; i < num_devices; i++) {
device = create_device(device);
/* Assign values */
device->id = i + 1;
sprintf(device->name, "Device%zu", device->id);
/* Print values */
printf("ID ----- [ %zu ]\n", device->id);
printf("Name --- [ %s ]\n", device->name);
/* Test free */
destroy_device(device);
}

printf("\n");
dev_malloc = malloc(num_devices * sizeof *dev_malloc);
for(i = 0; i < num_devices; i++) {
/* Assign values */
dev_malloc->id = i + 1;
sprintf(dev_malloc->name, "dev_malloc%zu", dev_malloc->id);
/* Print values */
printf("ID ----- [ %zu ]\n", dev_malloc->id);
printf("Name --- [ %s ]\n", dev_malloc->name);
}
/* Test free */
destroy_device(dev_malloc);

printf("\n");
dev_calloc = calloc(num_devices, sizeof *dev_calloc);
for(i = 0; i < num_devices; i++) {
/* Assign values */
dev_calloc->id = i + 1;
sprintf(dev_calloc->name, "dev_calloc%zu", dev_calloc->id);
/* Print values */
printf("ID ----- [ %zu ]\n", dev_calloc->id);
printf("Name --- [ %s ]\n", dev_calloc->name);
}
/* Test free */
destroy_device(dev_calloc);

return 0;
}

struct Devices* create_device(struct Devices *dev)
{
/* Not checking for memory error - just simple test */
return dev = malloc(sizeof *dev);
}

void destroy_device(struct Devices *dev)
{
if(dev != NULL) {
free(dev);
}
}

最佳答案

calloc(a,b)malloc(a*b) 是等价的,除了算术溢出或类型问题的可能性,以及 calloc 确保内存是零字节填充的。分配的内存可用于每个大小为 ba 元素数组(反之亦然)。另一方面,调用 malloc(b) a 次将导致 a 个大小为 b 的对象,其中可以独立释放并且它们在数组中(尽管您可以将它们的地址存储在指针数组中)。

希望这对您有所帮助。

关于c - malloc 和 calloc 在使用上的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4316696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com