简体   繁体   English

为什么这会导致段错误?

[英]Why does this cause a segfault?

I'm just trying to malloc an array of strings and copy input from a file into this array. 我只是试图分配一个字符串数组,并将文件中的输入复制到该数组中。 This combination of lines causes a segfault and I don't know why. 这些行的组合会导致段错误,我不知道为什么。

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

You've allocated space for an array of pointers, but you haven't initialized any of those pointers. 您已经为指针数组分配了空间,但尚未初始化任何这些指针。

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);

I think what you actually wanted to do here was allocate a memory for numLines pointers (strings) and then allocate memory for every string so that each of these is capable of holding 257 char s: 我认为您实际上想在这里做的是为numLines指针(字符串)分配一个内存,然后为每个字符串分配一个内存,以便每个字符串都能够容纳257 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);

just don't forget to clean it up once you don't need it anymore: 只是一旦您不再需要它,别忘了清理它:

for (i = 0; i < numLines; ++i)
    free(output[i]);
free(output);
output = NULL;
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.

if you want to read string 如果你想读字符串

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

if you want to read array of strings 如果您想读取字符串数组

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); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM