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

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

    While it is possible to get the meta-data that the memory allocator places preceding the allocated block, this would only work if the pointer is truly a pointer to a dynamically allocated block. This would seriously affect the utility of function requiring that all passed arguments were pointers to such blocks rather than say a simple auto or static array.

    The point is there is no portable way from inspection of the pointer to know what type of memory it points to. So while it is an interesting idea, it is not a particularly safe proposition.

    A method that is safe and portable would be to reserve the first word of the allocation to hold the length. GCC (and perhaps some other compilers) supports a non-portable method of implementing this using a structure with a zero length array which simplifies the code somewhat compared to a portable solution:

    typedef tSizedAlloc
    {
        size_t length ;
        char* alloc[0] ;   // Compiler specific extension!!!
    } ;
    
    // Allocating a sized block
    tSizedAlloc* blk = malloc( sizeof(tSizedAlloc) + length ) ;
    blk->length = length ;
    
    // Accessing the size and data information of the block
    size_t blk_length = blk->length ;
    char*  data = blk->alloc ;
    

提交回复
热议问题