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

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

    You can allocate more memory to store size:

    void my_malloc(size_t n,size_t size ) 
    {
    void *p = malloc( (n * size) + sizeof(size_t) );
    if( p == NULL ) return NULL;
    *( (size_t*)p) = n;
    return (char*)p + sizeof(size_t);
    }
    void my_free(void *p)
    {
         free( (char*)p - sizeof(size_t) );
    }
    void my_realloc(void *oldp,size_t new_size)
    {
         ...
    }
    int main(void)
    {
       char *p = my_malloc( 20, 1 );
        printf("%lu\n",(long int) ((size_t*)p)[-1] );
       return 0;
    }
    

提交回复
热议问题