简体   繁体   中英

Get all the lines of a char array and segfault

I am trying to put all the lines of a file in a char **. My function is very simple: the only parameter is a pointer to a char array, which containts the file. I first caculate the number of lines to allocate my char **. Once is it allocated, I use strtok_r to parse file. and then 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.

Then your while(c) loop does not end because you're not updating c in it. I leave that to you to fix.

Also, you have a memory leak with return NULL; . Put that check above array 's malloc() .

Sure you need the re-entrant version of strtok() ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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