为什么会导致段错误?

slm*_*ers 0 c arrays string malloc

我只是尝试malloc一个字符串数组并将文件中的输入复制到这个数组中.这种线条组合会导致段错误,我不知道为什么.

int count = 0;
char **output = (char**)malloc(numLines*257);
fgets(output[count], 257, input);
Run Code Online (Sandbox Code Playgroud)

Bar*_*mar 5

您已为指针数组分配了空间,但尚未初始化任何指针.

int count = 0;
char **output = malloc(numLines*sizeof(char *));
int i;
for (i = 0; i < numLines; i++) {
  output[i] = malloc(257);
}
fgets(output[count], 257, input);
Run Code Online (Sandbox Code Playgroud)