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

前端 未结 9 686
天命终不由人
天命终不由人 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:49

    It's up to the malloc implementor how to store this data. Most often, the length is stored directly in front of the allocated memory (that is, if you want to allocate 7 bytes, 7+x bytes are allocated in reality where the x additional bytes are used to store the metadata). Sometimes, the metadata is both stored before and after the allocated memory to check for heap corruptions. But the implementor can as well choose to use an extra data structure to store the metadata.

提交回复
热议问题