C++经典面试题(二)之常用库函数内部实现

1. memcpy

void* my_memcpy(void *dest, const char* src, size_t count)
{
	assert((dest != nullptr) && (src != nullptr));
	char* p_dest = (char*)dest;
	const char* p_src = (const char*)src;
	while (count--)
	{
		*p_dest++ = *p_src++;
	}
	return dest;
}

2. memset

void* my_memset(void* dst, const void* src, size_t count)
{
	char* p_dst = (char*)dst;
	const char* p_src = (const char*)src;
	assert((p_src != nullptr) && (p_dst != nullptr));
	while (count--)
	{
		*p_dst++ = *p_src++;
	}
	return p_dst;
}

3. memmove

void* my_memmove(void* dest, const void* src, size_t count)
{
	assert((dest != nullptr) && (src != nullptr));
	char* p_dest = (char*)dest;
	const char* p_src = (const char*)src;
	if (p_dest > p_src && p_dest < p_src + count) // 内存有重叠,逆向拷贝
	{
		p_dest += count - 1;
		p_src += count - 1;
		while (count--)
		{
			*p_dest-- = *p_src--;
		}
	}
	else // 此时无论是否重叠都可以使用正向拷贝
	{
		while (count--)
		{
			*p_dest++ = *p_src++;
		}
	}
	return dest;
}

4. strcpy

char* my_strcpy(char* dest, const char* src)
{
	assert((dest != nullptr) && (src != nullptr));
	char* ret = dest;
	while ((*dest++ = *src++) != '\0');
	return ret;
}

 

你可能感兴趣的:(C/C++)