How can I get the size of a memory block allocated using malloc()? [duplicate]

Possible Duplicates:
How can I get the size of an array from a pointer in C?
Is there any way to determine the size of a C++ array programmatically? And if not, why?

I get a pointer to a chunk of allocated memory out of a C style function. Now, it would be really interesting for debugging purposes to know how big the allocated memory block that this pointer points is.

Is there anything more elegant than provoking an exception by blindly running over its boundaries?

Thanks in advance, Andreas

EDIT:

I use VC++2005 on Windows, and GCC 4.3 on Linux

EDIT2:

I have _msize under VC++2005 Unfortunately it results in an exception in debug mode....

EDIT3:

Well. I have tried the way I described above with the exception, and it works. At least while I am debugging and ensuring that immediately after the call to the library exits I run over the buffer boundaries. Works like a charm.

It just isn't elegant and in no way usable in production code.


Solution 1:

It's not standard but if your library has a msize() function that will give you the size.

A common solution is to wrap malloc with your own function that logs each request along with the size and resulting memory range, in the release build you can switch back to the 'real' malloc.

Solution 2:

If you don't mind sleazy violence for the sake of debugging, you can #define macros to hook calls to malloc and free and pad the first 4 bytes with the size.

To the tune of

void *malloc_hook(size_t size) {
    size += sizeof (size_t);
    void *ptr = malloc(size);
    *(size_t *) ptr = size;
    return ((size_t *) ptr) + 1;
}

void free_hook (void *ptr) {
    ptr = (void *) (((size_t *) ptr) - 1);
    free(ptr);
}

size_t report_size(ptr) {
    return * (((size_t *) ptr) - 1);
}

then

#define malloc(x) malloc_hook(x)

and so on

Solution 3:

The C runtime library does not provide such a function. Furthermore, deliberately provoking an exception will not tell you how big the block is either.

Usually the way this problem is solved in C is to maintain a separate variable which keeps track of the size of the allocated block. Of course, this is sometimes inconvenient but there's generally no other way to know.

Your C runtime library may provide some heap debug functions that can query allocated blocks (after all, free() needs to know how big the block is), but any of this sort of thing will be nonportable.