为什么会导致段错误?

时间:2013-10-10 16:53:48

标签: c arrays string malloc

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

int count = 0;
char **output = (char**)malloc(numLines*257);
fgets(output[count], 257, input);

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

我认为你真正想要做的是为numLines指针(字符串)分配内存,然后为每个字符串分配内存,以便每个字符串能够保存257 {{1 }} S:

char

一旦你不再需要它就不要忘记清理它:

int i, count = 0;
char **output = malloc(sizeof(char*) * numLines);
for (i = 0; i < numLines; ++i)
    output[i] = malloc(257);
...
fgets(output[count], 257, input);

答案 2 :(得分:1)

int count = 0;
char **output = (char**)malloc(numLines*257);
fgets(output[count], 257, input); // here You are going wrong, with out allocating memory you are trying to read.

如果你想读取字符串

char *output = malloc(MAX_LENGTH+1); //allocate memory
    fgets(output[count], MAX_LENGTH+1, input);

如果你想读取字符串数组

char **output = malloc(MAX_NUM_STRINGS * sizeof(char *)); //allocate Number of pointers 
for(count=0;count<MAX_NUM_STRINGS;count++)
{   output[count]=malloc(SIZE_OF_EACH_STRING+1);  //allocate memory for each pointer,  
    //You are accessing with out allocating memory  
    fgets(output[count], SIZE_OF_EACH_STRING+1, input); 
}