c - 中止陷阱 : 6 error with strncat()

标签 c abort

我正在尝试编写必须实现库函数 strncpy、strncat 和 strncmp 版本的代码,但运行时出现 Abort trap: 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 部分可以工作。

最佳答案

大小为 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);

关于c - 中止陷阱 : 6 error with strncat(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42752275/

相关文章:

c - 如何在c中使用struct

c - 结构填充

java - 中止 AWS S3 上传

python - 有没有办法编写命令以中止正在运行的函数调用?

C# 线程多次调用但运行一次

c - 修改代码中的宏名称

无法正确打印txt文件

c - 为什么我的结构必须声明为指针?

git - 因 merge 冲突而重新建立基础 : How to undo?

http - 检测 HttpServlet 中中止的请求