Bit*_*lue -1 c memory arrays free
我必须安全地释放一个数组: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中的所有东西都已经过了.对于一个I malloced 5个字符串(每个指针4个字节) - > 20个字节.我如何解放整个char**?
除非分配了20个字节,否则不能释放20个字节.你只能释放一个街区.该块的大小在分配时指定.对于分配的每个块,您需要单独的取消分配.
您可以尝试使用realloc但不删除该块的任意部分来更改块的大小.
如果数组和数组中的指示项都已使用分配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);
}