Search code examples
cmemcpyreview

Is it safe to use memcpy like this?


memcpy(buf, buf + (pos - offset), len);

whereas,

0<=pos<=strlen(buf), 0<=offset<=strlen(buf)

Is it safe to use memcpy() in this scenario? If not, what could go wrong? Please suggest the best practice.


Solution

  • No it isn't. Use memmove instead.

    If the memory zones overlap when using memcpy, the behaviour is undefined. Though it may appear to work depending on the implementation.

    References: