开发者

Segmentation Fault while reading specificly 13 lines

char **getLines(FILE *pFile)
{
  int nLines = 0;
  size_t memRes = 0;
  char **lines = malloc(memRes);
  char *current = (char*) malloc(20);
  while(fgets(current, 20, pFile) != NULL)
    {
      memRes += sizeof(char*);
      lines = realloc(lines, memRes);
      lines[nLines] = malloc(20);
      strcpy(lines[nLines], current);
      nLines++;
    }
  free(current);
  return lines;
}

void printLines(char **lines)
{
  int lineI = 0;
  while(lines[lineI] != NULL)
    {
      printf("%s", 开发者_Go百科lines[lineI]);
      lineI++;
    }
}

First I get the lines then I print them. The odd thing about it is that my code fails when it has read exactly 13 lines of code and then prints them. I get a segmentation fault after printing the last line. It works with 12 lines and with 14 lines perfectly.


In your printLines function, "while(lines[lineI] != NULL)"

What is happening is that lines[lineI] isn't NULL, it just hasn't been allocated at the end. So because lineI is greater than nLines, it segfaults. You have to pass nLines into the function and use that to check boundries. "while (lineI < nLines)"


size_t memRes = 0;
char **lines = malloc(memRes);

Lines might be a bit too small.


You are assuming that the memory past the end of lines will contain a NULL, which it may or may not - it is uninitialized, so it could hold anything. You are getting 'lucky' for some small data sets, and it happens to contain zeros, so it works. For bigger data sets, you are running into an area of memory that has something else in it, and it is failing. If you want lines to be NULL past the set of pointers that hold the data from the fgets() calls, you need to allocate it big enough to hold an extra pointer, and set that space to NULL.

char **getLines(FILE *pFile)
{
  int nLines = 0;
  /* Start lines big enough to hold at least the NULL */
  size_t memRes = sizeof(char *);
  char **lines = malloc(memRes);
  lines[0] = NULL; /* the memory returned by malloc must be initialized */
  char *current = (char*) malloc(20);
  while(fgets(current, 20, pFile) != NULL)
  {
    memRes += sizeof(char*);
    lines = realloc(lines, memRes);
    lines[nLines + 1] = NULL;  /* Prepare the NULL to terminate display loop */
    lines[nLines] = malloc(20);
    strcpy(lines[nLines], current);
    nLines++;
  }
  free(current);
  return lines;
}

void printLines(char **lines)
{
  int lineI = 0;
  while(lines[lineI] != NULL)
  {
    printf("%s", lines[lineI]);
    lineI++;
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜