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

abc*_*xyz 1 c memory arrays memory-management

请考虑以下代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

程序在调用free函数时崩溃.我在SO看了类似的例子,它看起来几乎一样.我的代码有什么问题?

谢谢.

And*_*nle 5

你正在调用free()这个指针:

b[i] = "baz"
Run Code Online (Sandbox Code Playgroud)

该指针没有与分配malloc()(或者calloc(),realloc()等).