开发者

How can I get the size of a pointer of a segment of memory, mallocked by function "malloc" [duplicate]

This question already has answers开发者_高级运维 here: Closed 12 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜