Determine size of dynamically allocated memory in C

后端 未结 15 2562
孤街浪徒
孤街浪徒 2020-11-22 06:15

Is there a way in C to find out the size of dynamically allocated memory?

For example, after

char* p = malloc (100);

Is there

15条回答
  •  暖寄归人
    2020-11-22 07:00

    Here's the best way I've seen to create a tagged pointer to store the size with the address. All pointer functions would still work as expected:

    Stolen from: https://stackoverflow.com/a/35326444/638848

    You could also implement a wrapper for malloc and free to add tags (like allocated size and other meta information) before the pointer returned by malloc. This is in fact the method that a c++ compiler tags objects with references to virtual classes. Here is one working example:

    #include 
    #include 
    
    void * my_malloc(size_t s) 
    {
      size_t * ret = malloc(sizeof(size_t) + s);
      *ret = s;
      return &ret[1];
    }
    
    void my_free(void * ptr) 
    {
      free( (size_t*)ptr - 1);
    }
    
    size_t allocated_size(void * ptr) 
    {
      return ((size_t*)ptr)[-1];
    }
    
    int main(int argc, const char ** argv) {
      int * array = my_malloc(sizeof(int) * 3);
      printf("%u\n", allocated_size(array));
      my_free(array);
      return 0;
    }
    

    The advantage of this method over a structure with size and pointer

     struct pointer
     {
       size_t size;
       void *p;
     };
    

    is that you only need to replace the malloc and free calls. All other pointer operations require no refactoring.

提交回复
热议问题