开发者

Size of memory allocated on heap

Can you check the size memory allocated on heap if the buffer contains '0' characters?

char *c = new char[6]; //random s开发者_开发知识库ize memory
memset(c, 0, 6);


There's no reliable way to do that - you have to store that information yourself.

operator new[]() function can be implemented (and replaced by you) in whatever way so you just can't know the size unless you know the exact implementation in details.

In Visual C++ the default implementation for built-in types is to just forward calls to malloc() - then you could try _msize(), but again it's unportable and maybe even unreliable.


No, in general1 you can't. You have to store this information separately.

If you need to use that memory as a string or as an array, my advice is to use a std::string or std::vector, which do all this bookkeeping by themselves.


1. i.e. "as far as the standard is concerned"


I see that your question is MSVC++-specific; in that case, some heap-debugging helpers are provided, but they work only when the project is compiled in debug mode; I think there's some other compiler-specific function to get the allocated size, but it wouldn't work if custom allocators are used.

On the other hand, APIs like LocalAlloc let you know how big is the allocated chunk of memory (see e.g. LocalSize).

But again, I think that it's a cleaner design to keep track of this information by yourself.


No. You need to store the amount of allocated memory as a separate variable, and you need to take it with you whenever you want to do something with your allocated structure. This is cumbersome, but may be fast. As a safe and comfortable replacement use std::vector, boost::array, etc.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜