【发布时间】:2021-02-17 14:15:57
【问题描述】:
以下代码似乎运行良好:
char **func()
{
char **s = malloc(sizeof(char) * 5);
s[0] = "1101";
s[1] = "1001";
s[2] = "0001";
// s[3] = "1100";
return s;
}
int main()
{
char **s;
s = func();
printf("Hello World: %s", s[0]);
free(s);
return 0;
}
但如果我取消注释 s[3] = "1100"; 行,则会出现错误:
Error in `./a.out': free(): invalid next size (fast): 0x000000000259f010
为什么会这样,即使数组有足够的大小?
【问题讨论】:
-
sizeof(char)应该是sizeof(char *) -
sizeof(char) * 5大小不正确。您可以通过使用推荐的样式p = malloc(N * sizeof *p);来避免这个问题。 stackoverflow.com/questions/605845 -
如果
malloc中sizeof的参数是一个类型,它的*应该总是比你分配给的类型少一个。
标签: c string function pointers malloc