Determine size of dynamically allocated memory in C

后端 未结 15 2485
孤街浪徒
孤街浪徒 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 06:56

    Quuxplusone wrote: "Writing a function that can work on any of these void*s impossible, unless you can somehow tell from the pointer's value which of your heaps it came from." Determine size of dynamically allocated memory in C"

    Actually in Windows _msize gives you the allocated memory size from the value of the pointer. If there is no allocated memory at the address an error is thrown.

    int main()
    {
        char* ptr1 = NULL, * ptr2 = NULL;
        size_t bsz;    
        ptr1 = (char*)malloc(10);
        ptr2 = ptr1;
        bsz = _msize(ptr2);
        ptr1++;
        //bsz = _msize(ptr1);   /* error */
        free(ptr2);
    
        return 0;
    }
    

    Thanks for the #define collection. Here is the macro version.

    #define MALLOC(bsz) malloc(bsz)
    #define FREE(ptr) do { free(ptr); ptr = NULL; } while(0)
    #ifdef __linux__
    #include 
    #define MSIZE(ptr) malloc_usable_size((void*)ptr)
    #elif defined __APPLE__
    #include 
    #define MSIZE(ptr) malloc_size(const void *ptr)
    #elif defined _WIN32
    #include 
    #define MSIZE(ptr) _msize(ptr)
    #else
    #error "unknown system"
    #endif
    

提交回复
热议问题