[英]Abort trap: 6 error with strncat()
我正在嘗試編寫必須在其中實現庫函數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
的數組的索引為0
到n-1
。
當您這樣聲明數組時:
char dest[num];
然后執行以下操作:
dest[num] = '\0';
您正在訪問比數組末尾大1個字節的偏移量。 這樣做會調用未定義的行為 ,在這種情況下會導致崩潰。
由於您要將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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.