Is there a way in C to find out the size of dynamically allocated memory?
For example, after
char* p = malloc (100);
Is there
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