简体   繁体   English

无法释放动态分配的二维数组

[英]Failing freeing a 2d dimensional array dynamically allocated

Consider the following code: 考虑以下代码:

#include <stdio.h>

char** baz_alloc(int size)
{
    char ** b = malloc((size+1) * sizeof(char*));
    for (int i = 0; i < size; i++)
        b[i] = "baz";
    b[size] = NULL;

    return b;
}

void baz_print(char** baz)
{
    char** b = baz;
    while (*b != NULL)
    {
        printf("%s\n", *b);
        b++;
    }
}

void baz_free(char** baz)
{       
    int len = 0;
    char** b = baz;
    for (; *b != NULL; len++, b++);

    for (int i = 0; i < len; i++)
        free(baz[i]);
    free(baz);
}

int main()
{
    char** baz = baz_alloc(10);
    baz_print(baz);
    baz_free(baz);

    getch();
    return 0;
}

The program crashes at the call to the free function. 调用free函数时,程序崩溃。 I've looked at similar example here at SO and it looks pretty much the same. 我在SO上看过类似的示例,看起来几乎一样。 What is wrong in my code? 我的代码有什么问题?

Thanks. 谢谢。

You're calling free() on this pointer: 您正在此指针上调用free()

b[i] = "baz"

That pointer wasn't allocated with malloc() (or calloc() , realloc() , etc). 该指针未分配malloc() (或calloc()realloc()等)。

You can't free a string litteral 你不能乱扔垃圾

free(baz[i]);

tries to free from 试图摆脱

b[i] = "baz";

As a rule: Only free what you allocated, where you allocated it (in the topmost function causing the allocation), in reverse allocating order. 通常,只有:以相反的分配顺序释放分配的内容,分配的位置(在导致分配的最顶层函数中)。

For example : 例如 :

int main()
{
  char** baz = baz_alloc(10); //'creating' baz
  baz_print(baz); //using baz
  baz_free(baz); //freeing baz
  [...]
}

Is very good practice. 是很好的做法。

Your baz_free function only needs to use 1 free as only 1 malloc was called in baz_alloc : 您的baz_free函数仅需使用1 free因为在baz_alloc仅调用了1个malloc

//Allocation
char ** b = malloc((size+1) * sizeof(char*));

//Freeing
free(b); // or in your function free(baz);

If your baz_alloc function had b[i] = malloc(...) your baz_free code would be -almost- correct (You don't need to iterate twice, you could call free(b) in your first loop). 如果您的baz_alloc函数具有b[i] = malloc(...)您的baz_free代码几乎是正确的(您不需要重复两次,可以在第一个循环中调用free(b) )。

this loop: 这个循环:

for (int i = 0; i < len; i++)
    free(baz[i]);

should not exist because the memory was never allocated. 应该不存在,因为从未分配过内存。

However the following line: 但是以下行:

free(baz);

needs to be there as the initial array of pointers to char was created via a call to malloc(). 需要到那里,因为通过调用malloc()创建了指向char的指针的初始数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM