如果字符串不是使用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