If free() knows the length of my array, why can't I ask for it in my own code?

前端 未结 9 660
天命终不由人
天命终不由人 2020-12-02 18:20

I know that it\'s a common convention to pass the length of dynamically allocated arrays to functions that manipulate them:

void initializeAndFree(int* anArr         


        
9条回答
  •  一整个雨季
    2020-12-02 18:48

    You can't get it because the C committee did not require that in the standard.

    If you are willing to write some non-portable code, you may have luck with:

    *((size_t *)ptr - 1)
    

    or maybe:

    *((size_t *)ptr - 2)
    

    But whether that works will depend on exactly where the implementation of malloc you are using stores that data.

提交回复
热议问题