简体   繁体   English

获取char数组和segfault的所有行

[英]Get all the lines of a char array and segfault

I am trying to put all the lines of a file in a char **. 我试图将文件的所有行都放在char **中。 My function is very simple: the only parameter is a pointer to a char array, which containts the file. 我的函数非常简单:唯一的参数是指向包含文件的char数组的指针。 I first caculate the number of lines to allocate my char **. 我首先计算要分配char **的行数。 Once is it allocated, I use strtok_r to parse file. 分配好之后,我将使用strtok_r来解析文件。 and then Segfault. 然后是Segfault。 I wanted to know if it was possible to do that with this way? 我想知道是否可以用这种方式做到这一点?

char **getlines(char *file)
{
  int i = 0;
  int nblines = 0;
  while (file[i] != '\0')
  {
    if (file[i] == '\n')
      nblines++;
    i++;
  }
  char **array = malloc(sizeof(char*) * nblines);
  char *saveptr;
  if (nblines == 0)
    return NULL;
  int a = 0;
  char *c = strtok_r(file, "\n", &saveptr);
  while (c)
  {
    array[a] = strtok_r(NULL, "\n", &saveptr);
    a++;
  }
  return array;
}

Should be: 应该:

char **array = malloc(sizeof(char*) * nblines);

which allocates an array of pointers to your lines. 它为行分配了一个指针数组。

It's confusing to speak about a file while you're actually having a char* string. 当您实际上有一个char*字符串时,谈论一个file会令人困惑。

Then your while(c) loop does not end because you're not updating c in it. 然后, while(c)循环不会结束,因为您没有在其中更新c I leave that to you to fix. 我把这个留给你去解决。

Also, you have a memory leak with return NULL; 此外,您还会发生内存泄漏,并return NULL; . Put that check above array 's malloc() . 将该检查放在arraymalloc()上方。

Sure you need the re-entrant version of strtok() ? 确定需要strtok()的可重入版本吗?

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

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