Does memmove use dynamic memory for its temporary array

£可爱£侵袭症+ 提交于 2020-01-04 05:36:11

问题


According to C11 N1570 standard draft:

7.24.2.2 "The memmove function":

The memmove function copies n characters from the object pointed to by s2 into the object pointed to by s1. Copying takes place as if the n characters from the object pointed to by s2 are first copied into a temporary array of n characters that does not overlap the objects pointed to by s1 and s2, and then the n characters from the temporary array are copied into the object pointed to by s1

So if I choose to move a buffer of size 32K using (file_size = 32K)

memmove(io_Buffer, io_Buffer+17, file_size);

won't the temp buffer be of size 32K?

Question

Can the program allocate dynamic memory on its own? Does it allocate and free the memory in that one line?


回答1:


I think you missed the "as if" in that sentence. That means the effects will be the same as if it did that, not that it will actually do that. I've never seen an implementation of memmove that actually uses a temporary array.




回答2:


The memmove is not a single implementation in modern compilers; it is considered an intrinsic instead. It is easiest to show with an example how the "as if" works:

#include <string.h>

void test_memmove(void * restrict dst, const void * restrict src, size_t n) {
    memmove(dst, src, n);
}

the restrict in parameters tell that the memory accessed through the pointers do not overlap. So GCC knows to compile this to

test_memmove:
        jmp     memcpy

Because the compiler was able to take the restrict into account and "prove" that the memory areas pointed to by these 2 do not overlap, the call to memmove was immediately changed to a (tail) call to memcpy!



来源:https://stackoverflow.com/questions/55370165/does-memmove-use-dynamic-memory-for-its-temporary-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!