malloc函数的内存分配是如何工作的



char**res=(char**(malloc(sizeof(char*(*1(在这一行我使用了{sizeof(char*(*1},但我放置了多个不同长度的字符串。我不知道这是怎么回事,或者只是我的编译器没有显示错误/警告,或者这是正确的。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
char **res = (char **)malloc(sizeof(char *) * 1);
res[0] = "mang0000000o";
res[1] = "tango00000";
res[2] = "lango";
res[3] = "django";
for (int x = 0; x < 4; x++) {
puts(res[x]);
putchar('n');
}
return 0;
}

在这种情况下,您已经为长度为1的指针数组分配了内存。当你转向一个没有分配内存的元素时,你只会转向数组第一个元素之后的下一块内存。如果你试图在一个至少有一百个元素的循环中这样做,你几乎可以保证会出现分段错误。当您访问尚未分配的内存时,不会发生此错误,但当您访问已被某人占用的内存时会发生此错误。

在这种情况下,应该为sizeof(char*(*(n+1(分配内存,其中n是所需的元素数。您将向最后一个指针写入NULL,这样就可以方便地通过while或for对其进行迭代。

这应该有效:

#include<stdio.h>
#include<stdlib.h>
int main() {
const char **res = malloc(4 * sizeof *res); // Buff the size up a little bit
res[0] = "mang0000000o";
res[1] = "tango00000";
res[2] = "lango";
res[3] = "django";
for (int x = 0; x < 4; x++) {
puts(res[x]);
putchar('n'); // Note that 'puts' automatically adds a newline character 'n'
}

free(res);

return 0;
}

还要注意,您不一定需要string.h标头。希望这对你有用。

最新更新