Can I call memcpy() and memmove() with “number of bytes” set to zero?

前端 未结 2 1503
生来不讨喜
生来不讨喜 2020-12-01 05:38

Do I need to treat cases when I actully have nothing to move/copy with memmove()/memcpy() as edge cases

int numberOfBytes = ...
if(         


        
2条回答
  •  难免孤独
    2020-12-01 06:28

    As said by @You, the standard specifies that the memcpy and memmove should handle this case without problem; since they are usually implemented somehow like

    void *memcpy(void *_dst, const void *_src, size_t len)
    {
        unsigned char *dst = _dst;
        const unsigned char *src = _src;
        while(len-- > 0)
            *dst++ = *src++;
        return _dst;
    }
    

    you should not even have any performance penality other than the function call; if the compiler supports intrinsics/inlining for such functions, the additional check may even make the code a micro-little-bit slower, since the check is already done at the while.

提交回复
热议问题