【C语言】gets的安全问题

gets:由于没有办法限制读取的字符数的数量,不受信任的输入很容易导致缓冲区溢出。因此需要传入一个限制参数,防止数组越界,缓冲区溢出。

#include
#include
#include

int GetFiger(int m)  //中间层
{
	return m + 1;
}

void Mystrcpy_s(char *des, const char *str, int size)
{
	assert(des != NULL && size > 0 && str != NULL);
	if (des == NULL || size <= 0 || str == NULL)
	{
		return;
	}	

	int i;
	int _size = GetFiger(size);
	for (i = 0; str[i] != '\0' && i < _size - 1; i++)
	{
		des[i] = str[i];
	}
	des[i] = '\0';
}

int main()
{
	char* src = "abcdefghijk";
	printf("S未拷前为:%s\n", src);

	char str1[11] = { 0 };
	Mystrcpy_s(str1, src, 10);
	printf("A拷贝后为:%s\n", str1);

	char str2[15] = { 0 };
	strncpy_s(str2, src, 10);
	printf("B拷贝后为:%s\n", str2);

	return 0;
}

测试结果如下:
VS2013环境下测试

你可能感兴趣的:(C)