gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:49:26 26 4
gpt4 key购买 nike

我正在尝试编写必须实现库函数 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com