【问题标题】:Abort trap: 6 error with strncat()中止陷阱:strncat() 出现 6 个错误
【发布时间】:2017-03-12 19:48:18
【问题描述】:

我正在尝试编写必须实现库函数 strncpy、strncat 和 strncmp 版本的代码,但它在运行时给了我 Abort 陷阱:6 错误。任何想法都非常感谢:

#include<stdio.h> 
#include<string.h>

int main() {

    char str1[400];

    printf ("Enter the first string: ");
    fgets (str1, 400, stdin);

    char str2[400];

    printf ("Enter the second string: ");
    fgets (str2, 400, stdin);

    int num;

    printf ("Enter the number: ");
    scanf ("%d", &num);

    char dest[num];

    strncpy(dest, str2, num);
    dest[num] = '\0';

    printf ("strncpy is %s \n", dest);

    int lengthStr1 = strlen (str1);

    char str1copy [lengthStr1];
    strncpy(str1copy, str1, lengthStr1);
    str1copy [lengthStr1] = '\0';

    printf ("str1copy is %s \n", str1copy);

    strncat(str1copy, dest, num);
    printf ("strncat is %s\n", str1copy);
}

我知道我的 strncpy 部分有效。

【问题讨论】:

  • 你会在不把车送到车库的情况下让机械师修理你的车吗?你所谓的实现的功能在哪里?
  • dest[num] = '\0'; 出现越界。 str1copy [lengthStr1] = '\0'; 同上。
  • 也许我不太明白它们所说的实施是什么意思。我以为我们只需要使用这些功能。你将如何“实现”一个功能? @StoryTeller
  • return_type func_name(parameters) { statements_to_execute; } 是“实现”功能的方式。
  • 注意:标准库中定义的名称是保留的。你不能在你的代码中定义它们,也不能用不同的签名重新声明它们。

标签: c abort


【解决方案1】:

大小为n 的数组具有索引0n-1

当你像这样声明你的数组时:

char dest[num];

然后这样做:

dest[num] = '\0';

您正在访问数组末尾后一个字节的偏移量。这样做会调用undefined behavior,在这种情况下会导致崩溃。

由于您想将 num 字节复制到此数组中,因此大小应该再增加 1 以便为空字节腾出空间。

char dest[num+1];

那么设置dest[num] 就有意义了。

str1copy 也有类似的错误。但是在这种情况下,使用lengthStr1-1 作为偏移量是不够的。您从str1 复制lengthStr 字节,然后从dest 复制额外的num 字节。所以长度必须是它们的总和,再加上空终止字节的 1。

char str1copy [lengthStr1+dest+1];
strncpy(str1copy, str1, lengthStr1);
str1copy [lengthStr1] = '\0';

printf ("str1copy is %s \n", str1copy);

strncat(str1copy, dest, num);
str1copy [lengthStr1+dest] = '\0';
printf ("strncat is %s\n", str1copy);

【讨论】:

  • 不应该 null 在 dest[num] 中,但我们将 dest[] 的长度设为 num+1?因为我们有 num 数量的东西要放在 dest char 数组中。
  • @studentNeedHelp 如果您想复制num 字节,那么是的,它需要大1。此外,您没有为str1copy 留出足够的空间。查看我的编辑。
猜你喜欢
  • 1970-01-01
  • 2014-12-13
  • 2017-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
相关资源
最近更新 更多