strcpy 使用不.太.安全,strcpy_s只是windows下的,且在release版本也会弹出警告框,不太爽。
所以还是用strncpy比较好,在windows下可以预定义#define _CRT_SECURE_NO_WARNINGS(要定义在包含string.h头文件的前面),来屏蔽掉使用_s版本之类的warning。
但是使用strncpy也是有一个需要注意的地方,就是它有时是不会给你在字符串结尾加上‘\0‘的。
/* Copies count characters from the source string to the destination. If count is less than the length of source, NO NULL CHARACTER is put onto the end of the copied string. If count is greater than the length of sources, dest is padded with null characters to length count. so, should use like: char buf[N]; strncpy(buf, "123", N);// or: strncpy(buf, "123", N-1); buf[N-1] = ‘\0‘; //res: 1,2,3,\0(,\0...) 1,2,\0 (if N=3) */ char buf[4] = {}; char buf3[4] = {}; char buf2[] = "122343345"; strncpy(buf, buf2, 4); strcpy_s(buf3, 4, "123"); //char buf10[6]; char buf11[6]; strncpy(buf11, "123", 6);//1,2,3,\0,\0,\0 //memcpy(buf11, (void*)0x00001234, sizeof(buf11)); //memcpy(buf11, buf10, sizeof(buf11)); memcpy(buf11, buf11 - 6, sizeof(buf11));//mk dest uninit strncpy(buf11, "123", 5);//1,2,3,\0,\0,? memcpy(buf11, buf11 - 6, sizeof(buf11));//mk dest uninit strncpy(buf11, "123", 3);//1,2,3,?,?,? memcpy(buf11, buf11 - 6, sizeof(buf11));//mk dest uninit strncpy(buf11, "123", 1);//1,?,?,?,?,? // strncpy(buf11, "1234567", 6+1);//1,2,3,4,5,6[,7]: no assert, over write mem behind, then will crash
时间: 2024-11-10 22:03:03