C:编写字符串连接函数时的Segfault

时间:2015-02-02 05:42:35

标签: c

我正在尝试在C中连接一个字符串。我不允许使用strcat。我的程序编译没有错误。但是当我运行它时,我会遇到一个段错误。有人能告诉我什么是错的吗?谢谢。这是我的代码

char* concat(char** strs, unsigned int nstrs)
{
  unsigned int outlen = 0;
  char* output;
  int x;
  int y;

  for(x = 0; x < nstrs ; x++) {
    outlen += strlen(strs[x]);
   }

  output = (char *) malloc(outlen * sizeof(char));

  for(x = 0; x < nstrs ; x++) {
    for(y = 0 ; y < strlen(strs[x]) ; y++) {
     output[x+y] = strs[x][y];
}  
}

      return output;
}


int main(int argc, char *argv[])
{
  int strsize = 0;
  int x;

  for(x = 0; x < argc; x++) {
    strsize += strlen(argv[x+1]);
  }

  char** strs;
  strs = (char* *) malloc(sizeof(char)*strsize);

  for(x = 0; x < argc; x++) {
    strs[x] = argv[x+1];
  }

  concat(strs, (argc - 1));

  printf("%s", concat(strs, (argc -1)));

  free(strs);

  return 0;
}

3 个答案:

答案 0 :(得分:0)

strs = (char* *) malloc(sizeof(char)*strsize);

应该是

strs = malloc(sizeof(char *)* <num of pointers>);

strsize应在每个字符串中包含\0个字符。

即使您修复此问题,也会有数组超出限制的访问权限

  for(x = 0; x < argc; x++) {
    strsize += strlen(argv[x+1]);
  }

答案 1 :(得分:0)

这里的问题是

strsize += strlen(argv[x+1]);

xargc小1时,通过说argv[x+1],您正在访问超出范围的内存[请记住,数组索引从0开始]。

另外,请do not cast malloc()的返回值。

然后,char** strs;的内存分配逻辑出错了。 IMO,你需要的是像

strs = malloc(sizeof(char*) * (argc-1));

最后,正如其他答案建议的那样,您需要为output分配一个内存,而不是使用strlen()计算的源字符串长度的字节,因为strlen()不计算终止<{1}}是字符串表示所必需的。

答案 2 :(得分:0)

strs = (char* *) malloc(sizeof(char)*strsize);

你的明星不会加起来。如果您要分配char*数组,为什么使用sizeof(char)

output = (char *) malloc(outlen * sizeof(char));

这里你的sizeof是正确的,但你忘记了NUL终止字符串。您需要分配一个额外的字符,然后将其设置为'\0'