我有一个关于 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/