简体   繁体   English

堆上分配的内存大小

[英]Size of memory allocated on heap

Can you check the size memory allocated on heap if the buffer contains '0' characters? 如果缓冲区包含“ 0”字符,是否可以检查在堆上分配的大小内存?

char *c = new char[6]; //random size 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. operator new[]()函数可以以任何方式实现(并由您替换),因此除非您知道详细的确切实现,否则您将无法知道大小。

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. 在Visual C ++中,内置类型的默认实现是仅将调用转发给malloc() -然后您可以尝试_msize() ,但是_msize()移植甚至不可靠。

No, in general 1 you can't. 不,通常1您不能。 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. 如果您需要将该内存用作字符串或数组,我的建议是使用std::stringstd::vector ,它们可以自己完成所有簿记工作。


1. ie "as far as the standard is concerned" 1.即“就标准而言”


I see that your question is MSVC++-specific; 我发现您的问题是MSVC ++特有的; 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 eg LocalSize ). 另一方面,诸如LocalAlloc API会让您知道分配的内存块有LocalSize (请参阅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. 作为安全舒适的替代品,请使用std :: vector,boost :: array等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM