strncpy使用小结

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值