gpt4 book ai didi

c - 我必须释放结构内的数组吗?

转载 作者:IT王子 更新时间:2023-10-28 23:31:14 26 4
gpt4 key购买 nike

如果我有一个结构:

struct Rec
{
uint16_t vals[500];
};


Rec * prec = malloc(sizeof(Rec));
//Rec * prec = (Rec *) malloc(sizeof(Rec)); This code was my original and is incorrect.
// See Below for details.

// initialize everything in vals

这段代码是否足以释放所有使用的内存?

free(prec);

或者我必须单独释放数组吗?

最佳答案

这就够了。
您没有单独分配数组,因此只需释放分配的指针就足够了。

遵守规则:
您应该只在 malloc 返回给您的地址上调用 free,否则将导致 Undefined Behavior

引用文献:
c99 标准:7.20.3.2 免费功能

Synopsis
#include
void free(void *ptr);

Description:
The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc,or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

Returns
The free function returns no value.

关于c - 我必须释放结构内的数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8199793/

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