首页 文章

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

提问于
浏览
-2

我正在尝试编写代码,我必须实现库函数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 回答

  • 2

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

相关问题