Почему малло c выбрасывает сегфо? - PullRequest
0 голосов
/ 27 апреля 2020

Я пишу пользовательский конвейер. В следующем коде я получаю segfault при получении следующей группы аргументов.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

char** GetArgs(char* argv[], int argc, int* curInd) {
  int rhs = *curInd;
  while (rhs != argc && *argv[rhs] != '|') {
    ++rhs;
  }
  size_t size = rhs - *curInd + 1;
  char** retArgv = malloc(sizeof(char*) * size); // when call 2nd time malloc throw segfault
  if (retArgv == NULL) {
    perror("malloc args error");
    exit(1);
  }
  for (int i = *curInd; i < rhs; ++i) {
    retArgv[i - *curInd] = argv[i];
  }
  retArgv[rhs] = NULL;
  if (rhs == argc) {
    *curInd = -1;
  } else {
    *curInd = rhs + 1;
  }
  return retArgv;
}

int main(int argc, char* argv[]) {
  int pipelineCnt = 0;
  for (int i = 1; i < argc; ++i) {
    if (*argv[i] == '|') {
      ++pipelineCnt;
    }
  }

  char*** args = malloc(sizeof(char**) * pipelineCnt);

  int argInd = 1;
  for (int i = 0; i < pipelineCnt; ++i) {
    args[i] = GetArgs(argv, argc, &argInd); // call
  }

  for (int i = 0; i < pipelineCnt; ++i) {
    free(args[i]);
  }
  free(args);

  return 0;
}

Я запускаю программу с терминала следующим образом:

./a.out ls -l \| wc -l \| wc -l

Это ошибка, которую я получил:

mallo c. c: 2401: sysmallo c: утверждение `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size)> = MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0) 'не удалось.

Какая у меня проблема?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...