问题描述:

Possible Duplicates:

How can I get the size of an array from a pointer in C?

Any tool to find size of memory allocated dynamically using malloc/realloc?

How can I get the size of a pointer of a segment of memory, mallocked by function malloc, if only given a pointer

???

网友答案:

Here is an example:

typedef struct _BlockHeader {
    int Size;
} BlockHeader;

void *MyMalloc(int size) {
    char *ptr = malloc(size + sizeof(BlockHeader));
    BlockHeader *hdr = (BlockHeader*)ptr;
    hdr->Size = size;
    return (ptr + sizeof(BlockHeader));
}

void MyFree(void *ptr) {
    char *myptr = (char*)ptr;
    free(myptr - sizeof(BlockHeader));
}

int GetPtrMallocedSize(void *ptr) {
    char *myptr = (char*)ptr;
    BlockHeader *hdr = myptr - sizeof(BlockHeader);
    return (hdr->size);
}

Pratically each memory block starts with an header, collecting memory block information. Of course also realloc and calloc shall be implemented, but memory block cannot be used by other software which expect "normal" malloced memory.

Another way to do this is to hash the pointer, and collect memory information by hooking the malloc/free functions.

I know that MS CRT uses this to keep track of heap overflow and memory leaks. I don't know if there are some sideeffect... actually I've never used it.

网友答案:

You cannot, at least not without knowing the internals of your implementations version of malloc and how it's data structure of allocated blocks looks like.

网友答案:

You can't. Since you allocated the memory in the first place, you're responsible for keeping track of what and how much you allocated.

网友答案:

You get the size of the pointer p with sizeof(p).

If you ask for the size of the memory chunk, that is used to fulfill the malloc call, this might be version specific.

网友答案:

There is no standard for this, so its implementation specific. On windows however, you can use _msize.

相关阅读:
Top