How do realloc and memcpy work?

前端 未结 8 1023
遇见更好的自我
遇见更好的自我 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:40

    Presuming you are talking about glibc, and since your questions are implementation dependent, it's probably best just to check the source:

    malloc.c

    memcpy.c

    The way I read it, the answers would be:

    1. O(N) --- there is no way to copy items in better than linear time.
    2. Occasionally large items will be copied when realloc() is used to shrink them.
    0 讨论(0)
  • 2020-12-01 03:43
    1. There is absolutely no way to copy N items faster than O(N). However, it might be able to copy multiple items at once, or use special processor instructions - so it still might be faster than you could do it yourself.
    2. I don't know for sure, but I'd assume that the memory is completely reallocated. That's the safest assumption, and it's probably implementation dependent anyway.
    0 讨论(0)
提交回复
热议问题