简体   繁体   English

中止陷阱:strncat()出现6个错误

[英]Abort trap: 6 error with strncat()

I am trying to write code where I must implement versions of the library functions strncpy, strncat, and strncmp but it gives me Abort trap: 6 error while running. 我正在尝试编写必须在其中实现库函数strncpy,strncat和strncmp版本的代码,但它给了我Abort trap:运行时6错误。 Any ideas are much appreciated: 任何想法都非常感谢:

#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);
}

I know that my strncpy section works. 我知道我的strncpy部分有效。

An array of size n has indexes 0 to n-1 . 大小为n的数组的索引为0n-1

When you declare your array like this: 当您这样声明数组时:

char dest[num];

Then do this: 然后执行以下操作:

dest[num] = '\0';

You are accessing an offset one byte past the end of the array. 您正在访问比数组末尾大1个字节的偏移量。 Doing so invokes undefined behavior , which in this case manifests in a crash. 这样做会调用未定义的行为 ,在这种情况下会导致崩溃。

Since you want to copy num bytes into this array, the size should be 1 more to make room for the null byte. 由于您要将num个字节复制到此数组中,因此大小应增加1以为空字节腾出空间。

char dest[num+1];

Then setting dest[num] makes sense. 然后设置dest[num]是有意义的。

There's a similar error with str1copy . str1copy也有类似的错误。 In this case however using lengthStr1-1 as the offset isn't enough. 但是,在这种情况下,使用lengthStr1-1作为偏移量是不够的。 You copy in lengthStr bytes from str1 then an additional num bytes from dest . 您从str1复制lengthStr个字节,然后从dest复制另一个num个字节。 So the length has to be the sum of those, plus 1 for the null terminating byte. 因此,长度必须是这些长度的总和,再加上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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM