gpt4 book ai didi

C - 释放一定量的内存(char**)

转载 作者:行者123 更新时间:2023-11-30 18:19:11 26 4
gpt4 key购买 nike

我必须安全地释放一个数组:char** a;它就像一个字符串列表。我知道其中有多少个 char* 。但我很难释放所有内存。有没有类似的函数可以用来释放 20 个字节?我尝试过:

for (int i = 0; i < length; i++)
if (a[i] != null)
free(a[i]); // some of a[i] ARE null, non-null have different sizes
free(a); // crashes here

但是我在 asm 调试时遇到运行时错误。a 中的所有内容都已被分配。对于我分配的 5 个字符串(每个指针 4 个字节)-> 20 个字节。如何释放整个 char**

最佳答案

除非您分配了 20 个字节,否则您无法释放 20 个字节。您只能释放一个 block 。该 block 的大小是在分配时指定的。对于分配的每个 block ,您需要单独取消分配。

您可以尝试使用 realloc 更改 block 的大小,但这并不会删除该 block 的任意部分。

如果数组和数组中的各个项都已使用 malloc 进行分配,那么您的方法是正确的。释放每个元素,然后释放数组:

char **arr = malloc (10 * sizeof (char*));
if (arr != NULL)
for (int i = 0; i < 10; i++)
arr[i] = malloc (50 + i * 10); // sizes 50, 60, 70, ..., 140

// Use the ten X-character arrays here
// (other than NULL ones from malloc failures, of course).

if (arr != NULL) {
for (int i = 0; i < 10; i++)
free (arr[i]); // Okay to free (NULL), size doesn't matter
free (arr);
}

关于C - 释放一定量的内存(char**),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14577900/

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