How do realloc and memcpy work?

前端 未结 8 1054
遇见更好的自我
遇见更好的自我 2020-12-01 02:49

I have two questions.

  1. Do realloc() and memcpy() copy the entries in an array to another in a way faster than just iterating on eac

8条回答
  •  無奈伤痛
    2020-12-01 03:33

    1. The performance of memcpy can't really be better than O(N) but it can be optimized so that it outperforms manual copying; for example, it might be able to copy 4 bytes in the time it takes you to copy 1 byte. Many memcpy implementations are written in assembly using optimized instructions that can copy multiple elements at a time which is usually faster than copying data one byte at a time.

    2. I don't quite understand this question, if you use realloc to decrease the size of memory and it succeeds (returns non-NULL), the new location will contain the same data as the old location up to the size of the new request. If the memory location was changed as a result of calling realloc (not usual when decreasing the size) the contents will be copied, otherwise no copying needs to happen as the memory hasn't moved.

提交回复
热议问题