首页 > 技术知识 > 正文

【C语言经典面试题】源码实现标准库函数memmove

你有面试中,要求写memmove的源码实现吗?本文给出一个参考写法!

1 需求说明2 源码实现2.1 函数申明2.2 功能实现3 源码测试4 小小总结

1 需求说明

题目大意如下:

请参考标准C库对memmove的申明定义,使用C语言的语法写出其实现源码。

2 源码实现

2.1 函数申明

通过查看man帮助,我们可以知道memmove函数的功能及其简要申明。

复制​ NAME memmove – copy memory area ​ SYNOPSIS #includevoid *memmove(void *dest, const void *src, size_t n); ​ DESCRIPTION The memmove() function copies n bytes from memory area src to memory area dest. The memory areas may overlap: copying takes place as though the bytes in src are first copied into a temporary array that does not overlap src or dest, and the bytes are then copied from the temporary array to dest. ​ RETURN VALUE The memmove() function returns a pointer to dest.

2.2 功能实现

以下是我的一个简单实现源码,仅供参考:

复制char *my_memmove(char* dest, const char *src, size_t len) { assert(dest && src && (len > 0)); if (dest == src) { ; } else if (dest <= src || (char *)dest >= ((char *)src + len)) { char *p = dest; int i; /* The same as memcpy */ for (i = 0; i < len; i++) { *p++ = *src++; } } else if (dest > src) { char *p = dest + len1; src += len1; int i; /* Copy data from back to front */ for (i = len1; i >= 0; i–) { *p— = *src–; } } ​ return dest; } ​ 3 源码测试

简单的测试代码如下:

复制#include #include int main(void) { char buf[30] = “123456789abcdef”; printf(“before-memcpy-buf: %s “, buf); my_memmove(buf + 5, buf, 3); printf(“after-memcpy-buf: %s “, buf); ​ printf(“before-memcpy-buf: %s “, buf); my_memmove(buf + 5, buf, 9); printf(“after-memcpy-buf: %s “, buf); ​ return 0; } ​

简单写了build.sh脚本做编译测试:

复制#! /bin/bash -e ​ CFLAGS=“-Wall -Werror” cmd=“gcc *.c $CFLAGS -o test”if [ $1 = “clean” ]; then rm -rf test echo “Clean build done !” exit 0 fiecho $cmd && $cmd

执行编译后,运行小程序的结果:

复制c_c++/memmove$ ./test before-memmove-buf: 123456789abcdef after-memmove-buf: 123451239abcdef ​ before-memmove-buf: 123451239abcdef after-memmove-buf: 12345123451239f ​

从运行结果上看,基本满足了题目要求,有心的读者可以进一步测试其他测试用例。

4 小小总结

memmove的源码实现,核心是考虑内存重合的部分,这是与memcpy最本质的区别,下回我们再介绍一下memcpy的实现。感谢大家的关注,谢谢。

审核编辑:汤梓红

猜你喜欢