为什么malloc抛出segfault?

时间:2020-04-27 11:32:24

标签: c segmentation-fault malloc

我正在编写自定义管道。在下面的代码中,当我获取下一个args组时,我会遇到段错误。

#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

这是我得到的错误:

malloc.c:2401:sysmalloc:断言`(old_top == initial_top(av)&& old_size == 0)|| ((unsigned long)(old_size)> = MINSIZE && prev_inuse(old_top)&&((unsigned long)old_end&(pagesize-1))== 0)'失败。

我遇到了什么问题?

0 个答案:

没有答案