gpt4 book ai didi

c - 如何 free() 由 malloc() 分配的结构数组?

转载 作者:行者123 更新时间:2023-12-02 11:22:47 29 4
gpt4 key购买 nike

我一直在开发一个使用结构作为字符串存储的项目。我声明了一个由 char 类型成员组成的结构:

struct datastore1
{
char name[50];
char address[50];
char email[50];
char number[50];
char idnum[50];
};

我知道我可以执行 char *name, char *address... 但假设我们指定它的最大长度为 50。然后在使用该结构的函数上,我对它进行了 malloc,索引大小为 30:

struct datastore1 *dsdata = malloc(30 * sizeof(struct datastore1));

据说我通过访问每个索引完成了将所有字符串复制到结构中,我应该如何释放调用 malloc 后使用的已分配内存?我尝试在程序末尾执行 free(dsdata) 但我不确定这是否是正确的方法。我应该单独释放每个索引吗?请赐教。预先感谢您的反馈!

最佳答案

How should i free the allocated memory that was used after calling malloc?

考虑下面的例子,

struct datastore1 *obj1 = malloc(sizeof(struct datastore1));
free(obj1);

这里obj1指向与datastore1大小相同的内存块,为了释放您需要发送分配的地址malloc.

enter image description here

同样,

struct datastore1 *obj2 = malloc(3 * sizeof(struct datastore1));
free(obj2);

obj2 指向大小为 3 * sizeof(datastore1) 的连续内存块,您需要将基地址传递给 free

enter image description here

Should i free each indexes individually?

不,因为内存块仅分配一次,您需要释放一次。

让我进一步扩展,

struct datastore1 *obj3[3];
for(int i=0;i<3;i++)
obj3[i] = malloc(sizeof(struct datastore1));

for(int i=0;i<3;i++)
free(obj3[i]);

这里obj3是指针数组,每个索引都指向内存的不同部分,因此需要单独释放。

enter image description here

<小时/>

注意:为简单起见,我没有考虑 malloc 的返回值。必须对 malloc 返回值进行空检查。

关于c - 如何 free() 由 malloc() 分配的结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60260095/

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