Determine size of dynamically allocated memory in C

后端 未结 15 2612
孤街浪徒
孤街浪徒 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:45

    This code will probably work on most Windows installations:

    template 
    int get_allocated_bytes(T* ptr)
    {
     return *((int*)ptr-4);
    }
    
    template 
    int get_allocated_elements(T* ptr)
    {
     return get_allocated_bytes(ptr)/sizeof(T);
    }
    

提交回复
热议问题