免费2D char数组

Flo*_*lus 2 c memory arrays free

我需要释放一系列指针.所以我设置了一个简单的容易出错的例子,说明了我要做的事情.

int main() {

    char ** strings = malloc(2);
    strings[0] = malloc(sizeof(char)*4);
    strings[1] = malloc(sizeof(char)*4);

    strings[0] = "ABCD";
    strings[1] = "EFGH";

    free(strings[1]);
}
Run Code Online (Sandbox Code Playgroud)

我相信我需要以相反的顺序释放指针,所以我从索引一开始.但是我收到此错误:

free(): invalid pointer: 0x0000000000400d49 ***

释放就像free(strings);清除索引零一样,但是再次调用它会引发错误:

double free or corruption (fasttop): 0x00000000008e5010 ***

擦除此指针数组的正确方法是什么?或者如果我创建阵列的方式有问题,请告诉我.

sim*_*onc 8

strings[0] = "ABCD"
Run Code Online (Sandbox Code Playgroud)

用指向字符串文字的指针替换指向已分配内存的指针"ABCD".你没有为此分配内存,所以无法释放它.

使用

strcpy(strings[0], "ABCD");
Run Code Online (Sandbox Code Playgroud)

复制到您分配的内存中.

请注意,这里仍然会有另外两个问题.首先,您需要为strings数组中的两个指针分配空间- 您当前只分配2个字节.其次,"ABCD"需要5个字节的存储空间(第5个字节用于nul终结符).因此,您需要为每个数组分配5个字节,或者更好的是,使用strdup(Posix而不是C标准函数)组合分配和字符串复制

char ** strings = malloc(2 * sizeof(*strings));
strings[0] = strdup("ABCD");
strings[1] = strdup("EFGH");
Run Code Online (Sandbox Code Playgroud)