gpt4 book ai didi

c - 在 char* 的静态数组上使用 free()

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

我有以下代码:

void fn(char *string , int flag)
{
static char* array_of_strings[100];
static int index = 0;

if(flag)
{
array_of_strings[index] = (char *)malloc(10);
strcpy(array_of_strings[index] , string);
index++;
}
else
{
//How should I deallocate the memory here?
index--;
}
}

如果遇到 else block ,array_of_strings[index] 会发生什么?它会自动解除分配还是会在 fn() 返回后保留?我应该使用这一行来代替评论吗:

array_of_strings[index] = 0;

或者我可以像这样使用 free() 吗:

free(array_of_strings[index]);

这会释放 malloc 分配的内存块吗?

最佳答案

这一切都OK:

/* Allocate an array to hold 100 char * pointers: OK */
static char* array_of_strings[100];

/* Allocate space to hold one 9-character string: OK */
array_of_strings[index] = malloc(10);

/* Free string: OK */
free(array_of_strings[index]);

这会让你伤心:

/* Whoops: step on the pointer, then try to free it.  Not good :( */
array_of_strings[index] = 0;
free(array_of_strings[index]);

Q: What will happen to the array_of_strings[index] if the else block is met? Will it be automatically dealocated or will it stay after fn() returns?

答:如果你 malloc 一些东西,它会保持分配状态直到你“free()”它......或者直到程序终止。

关于c - 在 char* 的静态数组上使用 free(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19236338/

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