我在我的程序中使用这个函数:
static void free_envp(char **envp)
{
free(envp);
}
无论在线还是在手册页中,我都不知道应该如何管理错误以及可能发生哪些错误。
有人知道我在使用它时应该注意什么吗?
最佳答案
free
函数被调用以释放已在堆上分配的内存。即通过 malloc
、calloc
或 realloc
。
您应该将 malloc
返回的指针传递给 free
函数。由于在某些情况下 malloc
可以返回 NULL
,因此将 NULL
作为参数传递给 free
是安全的,所以 free(NULL)
什么都不做。
此外,对于每个 malloc
,您应该只调用一次 free
函数。在尚未分配或已释放的指针上调用 free
是未定义的行为。
出于这个原因,如果您要再次使用它,在它被释放后将指针设置为 NULL
可能是个好主意。
int *p;
p = malloc(n * sizeof(int)); // n is size of the array
if (p == NULL)
{
// Take appropriate action, e.g. exit the program.
}
....
.....
// After all use of the memory is over, if allocated properly before.
free(p);
p = NULL;
关于c - 如何在 c 中使用 free() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53204010/