当前位置:   article > 正文

程序员成长之旅——C语言模拟实现strcpy和strncpy_编程程序实现strcpy 使用const保证参数操作的安全性

编程程序实现strcpy 使用const保证参数操作的安全性

程序员成长之旅——模拟实现strcpy和strncpy

链式表达式解释

https://www.cnblogs.com/hnrainll/archive/2011/04/29/2032868.html

Mystrcpy

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
char* Mystrcpy(char* dest,const char* src)
{
	char* ret = dest;
	assert(dest);
	assert(src);
	while (*dest++ = *src++)
	{
		;
	}
	return ret;
}
int main()
{
	char dest[20] = { 0 };
	char* src = "Hello";
	char* ret = Mystrcpy(dest,src);
	printf("%s\n", ret);
	system("pause");
	return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

在这里插入图片描述

Mystrncpy

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
char* Mystrncpy(char* dest, const char* src, int count)
{
	assert(dest);
	assert(src);
	char* ret = dest;
	while (count && (*dest = *src))
	{
		dest++;
		src++;
		count--;
	}
	if (count > 0)
	{
		while (count--)
		{
			*dest = 0;
		}
	}
	return ret;
}
int main()
{
	char dest[10]= "0";
	int count = 6;
	char* src = "Hello";
	char* ret = Mystrncpy(dest,src,count);
	printf("%s\n", ret);
	system("pause");
	return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

在这里插入图片描述

两个函数的安全性比较

在安全性方面,显然strncpy要比strcpy安全得多,strcpy无法控制拷贝的长度,不小心就会出现dest的大小无法容纳src的情况,就会出现越界的问题,程序就会崩溃。而strncpy就控制了拷贝的字符数避免了这类问题,但是要注意的是dest依然要注意要有足够的空间存放src,而且src 和 dest 所指的内存区域不能重叠。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/388345?site
推荐阅读
相关标签
  

闽ICP备14008679号