使用 calloc 和 freeing 分配内存

ant*_*009 5 c malloc free

海湾合作委员会 4.4.4 c89

\n\n

我有一个正在测试的程序。我创建一个名为 devname 的结构对象并分配内存,以便可以填充元素。我显示它们,然后释放分配的内存。

\n\n

但是,我收到以下错误:

\n\n
invalid operands to binary != (have \xe2\x80\x98struct Devices_names\xe2\x80\x99 and \xe2\x80\x98void *\xe2\x80\x99)\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是在我的 for 循环中用于显示结构元素的。但是,我觉得我正在测试 NULL 指针。

\n\n

还有一个问题,免费的有问题吗?

\n\n

非常感谢您的任何建议,

\n\n
#include <stdio.h>\n#include <stdlib.h>\n\nstatic struct Devices_names {\n#define MAX_NAME_LEN 80\n    int id;\n    char name[MAX_NAME_LEN];\n} *devname;\n\nstatic void g_create_device_names(size_t devices);\nstatic void g_get_device_names();\nstatic void destroy_devices();\n\nint main(void)\n{\n#define DEVICES 5\n    g_create_device_names(DEVICES);\n\n    g_get_device_names();\n\n    destroy_devices();\n\n    return 0;\n}\n\nstatic void g_create_device_names(size_t devices)\n{\n    size_t i = 0;\n    devname = calloc(devices, sizeof *devname);\n    if(devname == NULL) {\n        exit(0);\n    }\n\n    for(i = 0; i < devices; i++) {\n        devname[i].id = i;\n        sprintf(devname[i].name, "device: %d", i);\n    }\n}\n\nstatic void g_get_device_names()\n{\n    size_t i = 0;\n\n    for(i = 0; devname[i] != NULL; i++) { <-- ERROR HERE\n        printf("Device id --- [ %d ]\\n", devname[i].id);\n        printf("Device name - [ %s ]\\n", devname[i].name);\n    }\n}\n\nstatic void destroy_devices()\n{\n    while(devname != NULL) {\n        free(devname++);\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Jus*_*ers 6

由于您只有一次分配来创建整个devname数组,因此您只需检查该数组的NULL,并且只需要释放该数组。当您查看时devname,每个条目实际上是一个struct Devices_names,而不是指针,因此不能NULL以任何有意义的方式比较或释放它。在这种情况下,您将需要一个单独的变量来跟踪有多少条目:

for (i = 0; i < devname_count; i++) {
    printf("Device id --- [ %d ]\n", devname[i].id);
    printf("Device name - [ %s ]\n", devname[i].name);
}

...

free(devname);
devname = NULL;
devname_count = 0;
Run Code Online (Sandbox Code Playgroud)

  • 您正在为五个对象创建*空间*,但您实际上只分配一个连续的块。一个好的经验法则是,对“malloc()”或“calloc()”的每次调用都应该与对“free()”的一次调用完全匹配。 (3认同)