c - 移动数组中的数据会覆盖数据吗?

标签 c memcpy

我有一个关于 memcpy 的问题。我有一个缓冲区,想要将数据从缓冲区的后端移动到前端。像这样的事情:

int buffer[100];
memcpy(buffer, buffer + 10, 30);

存在重叠数据(元素 11 - 21),是否会丢失数据或将数据复制到前面?这是一个“好的做法”吗?

背景:我在微 Controller 上有一个大缓冲区,并且不想重新分配该缓冲区。它是一个 fifo 缓冲区,每次读取内容时,后面的数据都会移到前面。我这样做是为了避免微 Controller 上的内存碎片。

最佳答案

memcpy 的手册明确指出,当缓冲区重叠时不应使用它,在这种情况下,您应该使用 memmove:

The memcpy() function copies n bytes from memory area src to memory area dest. The memory areas must not overlap. Use memmove(3) if the memory areas do overlap.

为了完整起见,以下是 memmove 的说明:

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.

关于c - 移动数组中的数据会覆盖数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48309157/

相关文章:

ios - iOS 如何处理低级 C/Objective-C 代码的内存损坏?

C:从字符数组复制到 int

使用 C 中的 memcpy 将 2D 矩阵复制到 3D 矩阵

C++字节流

c - 如何在c中的函数中手动输入数组?

c - C 中的 %f 和 %lf 有什么区别?

c - 使用 C 为日历控制台应用程序添加选项卡

c - 时间测量总时间与 cpu 时间

c - 将缓冲区传递给 picohttpparser 会导致编译错误

c - 如何在linux内核的memcpy函数中添加一个hook?