【问题标题】:Segmentation Fault 11 Error Output分段故障 11 错误输出
【发布时间】:2015-02-03 08:17:53
【问题描述】:

我目前遇到了段错误,但我似乎无法弄清楚为什么...... 我正在制作一个连接字符串值的代码:

char* concat(char** strs, unsigned int nstrs)
{
  char* newstring;
  int length = 0;
  int j;
  int charcount;
  int strcount;
  int k = 0;
  for (j = 0; j <= nstrs - 1; j++) {
    length = sizeof(strs[j]) + length;
  }
  newstring = malloc(length);
  for (strcount = 0; strcount <= nstrs - 1; strcount++) {
    for (charcount = 0; charcount <= strlen(strs[strcount]) - 1; charcount++)     {
      newstring[k] = strs[charcount][strcount];
      k++;
    }
  }
  return newstring;

在我的主要功能中,我有...

  char* introname[] = {"My", "name", "is", "Trill-o"};
  printf("%s\n", concat(introname, 4));

【问题讨论】:

  • sizeof 没有做你认为的事情。
  • 它不计算字节数吗?这不是我在尝试将堆中的内存分配给“newstring”时想要的吗?
  • 它在编译时产生(除了这里不存在的晦涩的极端情况),您传入的类型的大小。strschar**,所以@987654326 @ 是char*,它的大小是指针的大小。要知道 C 中字符串的长度,请使用 strlen(),它实际上会将字符计数到字符串的末尾。

标签: c string pointers segmentation-fault


【解决方案1】:

在你的代码中,你需要改变

sizeof(strs[j])

strlen(strs[j])

永远记住,sizeof 不是函数,而是运算符。它返回提供的数据类型的大小。在你的代码中,strs[j] 的类型是 char *,所以 sizeof 将返回一个等于 sizeof(char *) 的值。

要获得字符串长度,你必须使用strlen()

也就是说,请注意,strlen() 不包括终止 null 的计数。因此,在malloc() 中使用length 时,您必须为多一个字节添加空间,例如

  newstring = malloc(length + 1);    // 1 more byte for storing the terminating null.

另外,您必须检查malloc() 的返回值以确保成功。如果malloc()失败,会返回NULL,后续使用newstring会导致UB。

根据逻辑部分,您的代码应为

 newstring[k] = strs[strcount][charcount];

并正确终止字符串

newstring[k] = '\0' ;

for 循环之外。

【讨论】:

    【解决方案2】:
    sizeof(strs[j])
    

    在函数中会给出sizeof(pointer) 而不是sizeof(array) 但是由于您有一个字符串,请使用strlen(strs[j]) 来获取字符串的长度。

    请记下为\0 字符分配内存。

    【讨论】:

      【解决方案3】:

      不要使用 sizeof 来获取字符串的长度。

      你需要使用 strlen。

       sizeof(strs[j]) ; // bad, will return the sizeof pointer which is 4 or 8 depending on the system
       strlen(strs[j]); // this is what you want.
      

      【讨论】:

        【解决方案4】:

        你的主要问题在这里:

            length = sizeof(strs[j]) + length;
        

        sizeof 没有给出所需的字符串长度,因为它是char *,而不是数组。你要的是strlen(strs[j]))

        另外,当你完成总长度后,在malloc 之前添加一个作为终止的NUL

        最后是这样的:

          newstring[k] = strs[charcount][strcount];
        

        应该是

          newstring[k] = strs[strcount][charcount];
        

        【讨论】:

          【解决方案5】:

          C 字符串也是 null 终止的字符数组。确保连接的字符串末尾有一个 \0。这是一个工作版本:string concatenation

          注意我还切换了数组的索引。我想这就是你想要的。

          newstring = malloc(length + 1); // for '\0' character
          ...
          newstring[k] = strs[strcount][charcount];
          ...
          newstring[length] = '\0' ;
          

          【讨论】:

            猜你喜欢
            • 2016-01-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多