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

前端 未结 9 658
天命终不由人
天命终不由人 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;
    }
    
    0 讨论(0)
  • 2020-12-02 18:57

    I know this thread is a little old, but still I have something to say. There is a function (or a macro, I haven't checked the library yet) malloc_usable_size() - obtains size of block of memory allocated from heap. The man page states that it's only for debugging, since it outputs not the number you've asked but the number it has allocated, which is a little bigger. Notice it's a GNU extention.

    On the other hand, it may not even be needed, because I believe that to free memory chunk you don't have to know its size. Just remove the handle/descriptor/structure that is in charge for the chunk.

    0 讨论(0)
  • 2020-12-02 18:59

    Besides Klatchko's correct point that the standard does not provide for it, real malloc/free implementations often allocate more space then you ask for. E.g. if you ask for 12 bytes it may provide 16 (see A Memory Allocator, which notes that 16 is a common size). So it doesn't need to know you asked for 12 bytes, just that it gave you a 16-byte chunk.

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