如果字符串不是使用strcpy
複製的,該程序工作正常,但我想知道原因?爲什麼strcpy會觸發錯誤?
#include <stdio.h>
#include <string.h>
int main()
{
int mat;
char test1[20]={"Hex"} ;
char test2[20]={"agonal"} ;
strcpy(test1,"Diagonal"); // the print outputs the concatenated test if strcpy is commented out
//printf("a=%c\nb=%c\n",test1[0],test1[1]);
printf("Concatenated test=%s", strcat(test1, test2));
return 0;
}
ERROR MESSAGE
*** buffer overflow detected ***: ./prog terminated
======= Backtrace: =========
/lib/libc.so.6(__fortify_fail+0x48)[0xb75b6ae8]
/lib/libc.so.6[0xb75b4b30]
/lib/libc.so.6[0xb75b3dcd]
./prog(__gxx_personality_v0+0x14d)[0x804858d]
./prog(__gxx_personality_v0+0x31)[0x8048471]
======= Memory map: ========
「Diagonal」+「agonal」大於10 –
這就是爲什麼喜歡'strncat'和'strncpy'這些指定最大大小的函數是個好主意。 – aschepler
看來,錯誤在上面的問題**中得到了糾正(數組大小從10變爲20)。這意味着現在所有的答案似乎都沒有任何意義。 – wildplasser