中止陷阱:strncat()出错6次

时间:2017-03-12 19:48:18

标签: 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部分有效。

1 个答案:

答案 0 :(得分:2)

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

当你声明你的数组时:

char dest[num];

然后这样做:

dest[num] = '\0';

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

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

char dest[num+1];

然后设置dest[num]是有意义的。

str1copy出现了类似的错误。在这种情况下,使用lengthStr1-1作为偏移量是不够的。您从lengthStr复制str1个字节,然后从num复制dest个字节。因此,长度必须是这些的总和,加上空终止字节为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);
相关问题