C free() routine and incremented array pointers

前端 未结 2 2022
有刺的猬
有刺的猬 2021-01-18 06:56

Will the free() routine work if I dynamically allocate an array and then pass, not the initial pointer, but a pointer to the middle of the array? Example:

相关标签:
2条回答
  • 2021-01-18 07:32

    Absolutely not. The value passed to free() must be exactly the same value returned by malloc(). In fact, to ensure this is the case, I would recommend you use a copy of the pointer if you need a pointer you can increment or otherwise modify.

    0 讨论(0)
  • 2021-01-18 07:49

    No

    (And "Yes", you do need to "set it back".)

    The API requires that you only pass to free() exactly what you got from malloc()1.


    1. Or a null pointer.

    0 讨论(0)
提交回复
热议问题