Determine size of dynamically allocated memory in

2018-12-31 20:26发布

Is there a way in C to find out the size of dynamically allocated memory?

For example, after

char* p = malloc (100);

Is there a way to find out the size of memory associated with p?

12条回答
余生请多指教
2楼-- · 2018-12-31 21:00

This code will probably work on most Windows installations:

template <class T>
int get_allocated_bytes(T* ptr)
{
 return *((int*)ptr-4);
}

template <class T>
int get_allocated_elements(T* ptr)
{
 return get_allocated_bytes(ptr)/sizeof(T);
}
查看更多
伤终究还是伤i
3楼-- · 2018-12-31 21:03

No, the C runtime library does not provide such a function.

Some libraries may provide platform- or compiler-specific functions that can get this information, but generally the way to keep track of this information is in another integer variable.

查看更多
一个人的天荒地老
4楼-- · 2018-12-31 21:05

comp.lang.c FAQ list · Question 7.27 -

Q. So can I query the malloc package to find out how big an allocated block is?

A. Unfortunately, there is no standard or portable way. (Some compilers provide nonstandard extensions.) If you need to know, you'll have to keep track of it yourself. (See also question 7.28.)

查看更多
伤终究还是伤i
5楼-- · 2018-12-31 21:10

Like everyone else already said: No there isn't.

Also, I would always avoid all the vendor-specific functions here, because when you find that you really need to use them, that's generally a sign that you're doing it wrong. You should either store the size separately, or not have to know it at all. Using vendor functions is the quickest way to lose one of the main benefits of writing in C, portability.

查看更多
泛滥B
6楼-- · 2018-12-31 21:11

There is no standard way to find this information. However, some implementations provide functions like msize to do this. For example:

Keep in mind though, that malloc will allocate a minimum of the size requested, so you should check if msize variant for your implementation actually returns the size of the object or the memory actually allocated on the heap.

查看更多
萌妹纸的霸气范
7楼-- · 2018-12-31 21:20

I would expect this to be implementation dependent.
If you got the header data structure, you could cast it back on the pointer and get the size.

查看更多
登录 后发表回答